[英]Typescript generic type inference not working
在使用 Typescript 时,我总是想知道为什么不能自动推断出这两种情况? 有什么合乎逻辑的原因吗? 你将如何克服这一点?
type Test1<T> = {
a: T,
b: T extends string ? object : number,
};
// Error: Generic type 'Test1' requires 1 type argument(s).
// I expect Typescipt to infer T from the `a` property
const test1: Test1 = {
a: "test1",
b: {bb: null},
};
type Options = "option1" | "option2";
type Test2<O extends Options> = O extends "option1"
? {a: O, b: string}
: {a: O};
const f = <O extends Options>(arg: Test2<O>) => {
// Error: Property 'b' does not exist on type 'Test2<O>'.
// I expect Typescript to infer O from the condition
if (arg.a === "option1") arg.b;
}
这是您第一个问题的答案:
type Test1<T> = {
a: T,
b: T extends string ? object : number,
};
const check = <T,>(arg: Test1<T>): Test1<T> => arg
const x = check({
a: "test1",
b: { bb: null },
})
const x1 = check({
a: 2,
b: { bb: null }, // error
})
const x2 = check({
a: 2,
b: 2, // ok
})
我刚刚创建了助手 function check
以进行可能的类型推断
第二个问题:
type TestA = {
a: 'option1';
b: string;
}
type TestB = {
a: 'option2';
}
type Test = TestA | TestB
const f = (arg: Test) => {
if (arg.a === "option1") {
arg.b // ok
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.