如何在打字稿中强制执行类型识别?



在打字稿中,如果你有两个接口并且作为联合类型,为什么它不区分你可以声明哪些类型成员?

interface IFish {
swim: () => void;
}
interface ICat {
meow: () => void;
}
type Pet = IFish | ICat;
const pet: Pet = {
meow: () => {
//
},
swim: () => {
//
}
};

接口定义对象必须具有哪些成员,但不定义对象可能没有哪些成员。 因此,允许IFish具有swim方法,反之亦然。

看看更新后的示例:

interface IFish {
swim: () => void;
meow: undefined;
}
interface ICat {
meow: () => void;
swim: undefined;
}
type Pet = IFish | ICat;
const pet: Pet = {  // compilation error here
meow: () => {
//
},
swim: () => {
//
}
};

这里明确指出,IFish不能定义meow,ICat不能定义swim。 但是,此方法的问题在于,如果您有 2 个以上的接口和方法,则必须在类型定义中添加大量这些undefined

最新更新