2017-05-31 52 views
2

如何根據函數的某個輸入參數返回帶有「selected」類型的區分聯合?TypeScript:使用「已選擇的選項」返回帶區分的聯合

type KeyValueDocument = { 
    key: "type-a"; 
    propA: string; 
} | { 
    key: "type-b"; 
    propB: string; 
} 

function getKeyValue(key: string): KeyValueDocument { 
    // ... implementation ... 
    assert(result.key == key); 
    return result; 
} 

const value = getKeyValue("type-b"); 

console.log(value.propB); // Bang! 

回答

4

你可以有不同的簽名不同的密鑰:

​​3210