簡體   English   中英

TypeScript 如何創建具有條件返回類型的函數?

[英]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('');

split 函數對字符串起作用,請注意這個

toFixed 函數對 Number 起作用,請注意這個

因此,如果您以正確的格式轉換 res 和 res2,然后應用正確的函數。 可能你可以得到你的預期結果。

我對您的代碼進行了一些更改。 (將 res 轉換為字符串並將 res2 轉換為數字)。 在此處此處查看您更改的代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM