我正在开发一个使用 cookie 的网络应用程序。要读取 cookie,我想编写这种类型的打字稿函数:
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;
}
是否有可能创建一个能够根据类型 T 表现不同的 getCookie 函数?
答案 0 :(得分:1)
首先,接口只存在于编译期,所以在代码中不可能对它们有条件。
条件返回类型确实存在,但似乎只是部分支持:
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,但它似乎没有修复就关闭了。