当为 arg1
放置类型保护时,我希望自动推断出 arg2
,但事实并非如此。
有人知道为什么这不起作用吗?最好的选择是什么?非常感谢!
您可以看到正在运行的类型 here 。只需将鼠标悬停在 arg2
上即可查看推断的类型。
function example<T extends 'foo' | 'bar'>(
arg1: T,
arg2: T extends 'foo' ? string : number
) {
if (arg1 === 'foo') {
arg2 // should be string?
}
if (arg1 === 'bar') {
arg2 // should be number?
}
}
但是,调用该函数确实正确应用了第二个参数类型:
这是使用基于泛型的类型化对象的另一个示例:
type Test <T extends boolean> = {
multiple: T;
value: T extends true ? string : number;
};
// this doesn't work?
function test <T extends boolean>(a: Test<T>) {
if (a.multiple) {
a.value // string | number?
}else{
a.value // string | number?
}
}
// this works!
function test2 (a: Test<true> | Test<false>) {
if (a.multiple) {
a.value // is string
}else{
a.value // is number
}
}
最佳答案
我使用这两种解决方案来获得条件参数:
解决方案 1(推荐):使用对象作为参数
type Args = { arg1: 'foo'; arg2: string } | { arg1: 'bar'; arg2: number };
function example(args: Args): void {
if (args.arg1 === 'foo') {
args.arg2; // It's string
}
if (args.arg1 === 'bar') {
args.arg2; // It's number
}
}
解决方案 2:使用参数对象
type Args = ['foo', string] | ['bar', number];
function example(...args: Args): void {
if (args[0] === 'foo') {
args[1]; // It's string
}
if (args[0] === 'bar') {
args[1]; // It's number
}
}
关于Typescript:基于泛型进行推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65038122/