TypeScript:可选的合并类型

标签 typescript typescript-typings

我有类型 a并输入 b ,但这应该适用于任何数量的类型。

type a = {
    first: number
}

type b = {
    second: string
    third: string
}
我想创建一个可以选择合并所有这些类型的类型,所以如果它有 second字段,它应该有 third field 也是,但不必同时拥有它们:
好的:
const aa = {
     first: 1,
     second: "hi",
     third: "hello"
}

const ab = {
     first: 1
}

const ac = {
     second: "hi",
     third: "hello"
}
坏的:
const bb = {
     first: 1,
     second: "hi"
}
我怎么能定义这样的类型?

最佳答案

type None<T> = {[K in keyof T]?: never}
type EitherOrBoth<T1, T2> = T1 & None<T2> | T2 & None<T1> | T1 & T2

type abcombined = EitherOrBoth<a,b>
查看更详细的示例:Can Typescript Interfaces express co-occurrence constraints for properties
Playground link

关于TypeScript:可选的合并类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63854469/

相关文章:

javascript - TypeScript:VS Code 中的 Array.reduce 函数报告错误

typescript - 如何正确推断 Svelte Prop 类型?

typescript - es6 和 es2017 之间 tsconfig.json 中的 'lib' 属性的区别?

继承类的 typescript 返回类型

typescript - 我如何决定 @types/* 是进入 `dependencies` 还是 `devDependencies` ?

typescript - 使用类装饰器,我可以获得类类型实例的类型吗?

typescript - 从实例获取类(静态)属性

reactjs - 在 SSR 期间获取主机名

javascript - 输入 onChange w/React & TypeScript 错误 : jsx no-lambda no-bind

node.js - Graphql apollo 服务器解析器参数类型