gpt4 book ai didi

typescript :如何根据类型进行分支

转载 作者:搜寻专家 更新时间:2023-10-30 21:46:10 24 4
gpt4 key购买 nike

我有这样的东西:

interface A {
a1: string;
a2: number;
a3: boolean;
}

interface B {
b1: number;
b2: boolean;
b3: string;
}

function foo<K1 extends keyof A, K2 extends keyof B>(input: K1 | K2) {
if (input keyof A ) { // <--- THIS IS WRONG!
console.log('got A type');
} else {
console.log('got B type');
}
}

foo('a1');
foo('b2');

如何更新 if 语句以使其根据类型正确分支?

我已经尝试过keyof、typeof、instanceof ....没有一个是正确的。

最佳答案

接口(interface)在运行时不存在,它们完全是编译时构造。因此无法在表达式中使用类型,因为在运行代码时类型不会存在。

我们能做的最好的事情是创建一个包含接口(interface)所有键的对象,编译器保证包含接口(interface)的所有键并且只包含接口(interface)的键

然后我们可以在自定义类型保护中使用这个对象来帮助编译器缩小键的类型。

一般的解决方案看起来像这样:

interface A {
a1: string;
a2: number;
a3?: boolean;
}

interface B {
b1: number;
b2: boolean;
b3: string;
}

// Factory function for key type-guards
function interfaceKeys<T>(keys: Record<keyof T, 0>) {
return function (o: PropertyKey): o is keyof T {
return o in keys;
}
}
// The objects here are compiler enforced to have all the keys and nothing but the keys of each interface
const isAkey = interfaceKeys<A>({ a1: 0, a2: 0, a3: 0 })
const isBkey = interfaceKeys<B>({ b1: 0, b2: 0, b3: 0 })


function foo<K1 extends keyof A, K2 extends keyof B>(input: K1 | K2) {
if (isAkey(input)) { // custom type guard usage
console.log('got A type');
input // is K1
} else {
console.log('got B type');
input // is K2
}
}

foo('a1');
foo('b2');

关于 typescript :如何根据类型进行分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54543838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com