首页 > 解决方案 > 如何在打字稿中强制执行类型歧视?

问题描述

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

interface IFish {
  swim: () => void;
}

interface ICat {
  meow: () => void;
}

type Pet = IFish | ICat;

const pet: Pet = {
  meow: () => {
    //
  },
  swim: () => {
    //
  }
};

标签: typescript

解决方案


你的接口定义了一个对象必须有哪些成员,但它没有定义一个对象可能没有哪些成员。因此,允许 anIFish拥有一个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到类型定义中。


推荐阅读