[英]TypeScript how to create a function with conditional return type?
我想寫一個有條件返回類型的函數。 如果函數被傳遞一個 'val1' 作為參數,它返回一個字符串類型,如果 'val2' 返回數字類型,依此類推。
簡單的例子
游樂場: 這里
const store = {
val1: 'string',
val2: 1,
val3: true
};
type INames = keyof typeof store; // "val1" | "val2" | "val3"
const getFromStore = (paramName: INames) => {
return store[paramName];
};
const res = getFromStore('val1'); // return type is string | number | boolean instead of string
res.split(''); // error
const store = {
val1: 'string',
val2: 1,
val3: true
};
const getFromStore = <K extends keyof typeof store>(paramName: K) => {
return store[paramName];
};
const res = getFromStore('val1');
res.split('');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.