[英]Typescript: detect the generic type of a function
我正在開發一個使用 cookies 的 web 應用程序。 要讀取 cookie,我想寫一個 typescript function 這種類型:
let cookie1: number = getCookie<number>("fake_int_name");
let cookie2: boolean = getCookie<boolean>("fake_bool_name");
let cookie3: string = getCookie<string>("fake_string_name");
function getCookie<T>(name: string): T {
...
let cookie_value: string = "fake_cookie_value";
if(T is number)
return parseInt(cookie_value);
if(T is boolean)
return cookie_value == "true";
return cookie_value;
}
是否可以創建一個 getCookie function 能夠根據類型 T 表現不同?
首先,接口只存在於編譯時,因此不可能在代碼中對其有條件。
條件返回類型確實存在,但似乎只是部分支持:
enum ResultType {
INT = 'int',
BOOL = 'bool',
STRING = 'string',
}
interface TypeMap {
int: number;
bool: boolean;
string: string;
}
function getCookie<K extends ResultType>(name: string, type: K): TypeMap[K] {
let cookieValue;
// ...
switch (type) {
case ResultType.INT:
return parseInt(cookieValue, 10) as any;
case ResultType.BOOL:
return (cookieValue === 'true') as any;
case ResultType.STRING:
return cookieValue as any;
}
}
// usage:
getCookie('foo', ResultType.INT); // compiler correctly assumes number as return type
getCookie('foo', ResultType.BOOL); // compiler correctly assumes boolean as return type
您可以在此處看到返回類型被強制轉換為any
。 編譯器無法正確推斷此類型。 解決此問題的問題是https://github.com/microsoft/TypeScript/issues/24929 ,但似乎沒有修復就關閉了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.