typescript - 如何在打字稿中强制执行类型歧视?
问题描述
在打字稿中,如果您有两个接口并作为联合类型,为什么不区分您可以声明哪些类型成员?
interface IFish {
swim: () => void;
}
interface ICat {
meow: () => void;
}
type Pet = IFish | ICat;
const pet: Pet = {
meow: () => {
//
},
swim: () => {
//
}
};
解决方案
你的接口定义了一个对象必须有哪些成员,但它没有定义一个对象可能没有哪些成员。因此,允许 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
到类型定义中。
推荐阅读
- ffmpeg - ffmpeg 从 MOV 转换为 mp4 - 如何保存创建日期
- visual-studio - Windows下构建发布版abseil-cpp静态二进制库
- java - 如何在控制器中获取通配符路径变量
- docker - 在 Jenkins 构建中运行 docker 脚本时出现编译错误
- javascript - React useEffect() 正在重新渲染,但动态值未反映在屏幕上
- javascript - 如何在 React 的 Ionic 5 中锁定幻灯片
- sql - 根据 WHERE 条件创建列
- python - Django - 模型中的时间戳字段
- python - 使用 BeautifulSoup 和 RegEx 或 Lambda 循环 URL 以进行匹配?
- spss - 计算每组中的一系列值