typescript - 排他或打字稿中的类型
问题描述
我正在尝试制作一个打字稿函数,该函数接受一个匹配两个条件之一的参数:
type A = {
x: string
}
type B = {
y: string
}
function testFunc(param: A | B) {
...
}
但是打字稿让我用两个键调用函数:
testFunc({x: "x", y: "y"})
联合类型不应该使这个函数需要A或B吗?
在这里展示问题的游乐场
解决方案
您可以使用函数重载来做到这一点:
type One = {
x: string
}
type Two = {
y: string
}
function test(props: One): void;
function test(props: Two): void;
function test(props: (One | Two)) {
console.log(props)
}
test({
x: 'a',
}) // ok
test({
y: 'f'
}) // ok
test({
x: 'a',
y: 'f'
}) // error
推荐阅读
- react-native - Redux 操作返回未定义?
- python - 在其各自的 one-hot 编码列中填充分类数据的值
- sql-server - 无法连接到 travis 中 docker 内的 SQL Server 数据库
- php - 使用php转换数字
- javascript - Angular 4 的密码正则表达式失败
- javascript - React 无法识别 reducer 中的状态变化
- spring-boot - 带有 gradle 的 Springboot 项目因错误而失败 - 多个绑定
- r - 根据月营业额查找月份
- python - Python - 在 Mac 上安装 opencv 时遇到问题(几个月前 opencv 工作正常之后)
- node.js - Firebase 云功能 - Reference.update 失败