比较 JS 对象键以查看它是否是相同的 TypeScript 类型



想象一下这个代码场景:


type A = {
keyOne: string;
keyTwo: string;
};
type B = {
keyThree: string;
keyFour: string;
};
type C = {
unionKey: A | B;
keyFive: string;
};
type CA = {
unionKey: A;
keyFive: string;
};
type CB = {
unionKey: B;
keyFive: string;
};
const obj: C = {} as C;
if ('keyOne' in obj.unionKey) {
obj.unionKey.
}
const handleType = (obj: C): CA | CB => {
if ('keyOne' in obj.unionKey) {
return obj as CA;
} else return obj as CB;
};
const result = handleType({
unionKey: {
keyThree: 'sdfsd',
keyFour: 'sadfasd',
},
keyFive: 'sdfsd',
});
result.unionKey. // TS is get confused here and could not suggest me correct type which I'm looking for (keyThree & keyFour)

考虑有obj,我如何检查unionKey上的类型,看看它遵循的是哪种类型?如果是类型A,我想做X工作,如果是B,我要做Y工作。

问题是比较JS值和TS类型!

将函数更改为使用泛型类型,则该类型将失效。

例如。。

function handleType<T extends C>(obj: T) {
if ('keyOne' in obj.unionKey) {
return obj;
} else return obj;
};

TS游乐场

最新更新