我试图了解 TypeScript 条件类型的工作原理。这是我的代码。有类型错误:
interface MyType {
name: string;
}
const testFunc = <T extends MyType | string>(
what: T
): T extends MyType ? MyType : string => {
if (typeof what === 'object') {
return what['name'];
}
return what;
};
Run Code Online (Sandbox Code Playgroud)
正确的用法是什么?
是否可以根据参数返回函数的类型?
我看到了基于字符串文字类型参数的变量返回类型,但它使用了重载。在这里,我有 100 多种类型,所以我不想进行重载。
interface Registry {
A: number,
B: string,
C: boolean,
// ... 100 more types like this
}
function createType<T = Registry[typeof myType]>(myType: keyof Registry, value: any): T {
// do some magic
// ...
return value;
}
const a = createType('A', 2); // Expected type: number. Actual: error above
Run Code Online (Sandbox Code Playgroud)