【问题标题】:One of two property name两个属性名称之一
【发布时间】:2021-08-28 04:26:49
【问题描述】:
type B = {
 c: string
}
    
type T = {
  a: string
  b: B
}

我想让T2看起来像

type T2 = {
  a: string
  ['b' or 'prefixB']: B
}

基本上我希望 T 具有 a 和 b 或 prefixB 属性 - 你知道如何以简单的方式做到这一点吗?类似于两者之一的东西

【问题讨论】:

标签: typescript typescript-typings


【解决方案1】:
type Aa = {a: string}
type T2 =  Aa & ({prefixB: string} | {b: string})

const foo: T2 = {
  a: "a",
  b: "b"
}
foo.a // a
foo.b // b
foo.prefixB // Property 'prefixB' does not exist

const foo2: T2 = {
  a: "a",
  prefixB: "prefixB"
}
foo2.a // string
foo2.prefixB // prefixB
foo2.b // Property 'b' does not exist

我认为这是工作


更新

type Aa = {a: string}
type B = {
  c: string
}

type T2 =  Aa & ({prefixB: B} | {b: B})

const foo: T2 = {
  a: "a",
  b: {
    c: "obj"
  },
}
foo.a // a
foo.b // { c: "obj" }
foo.prefixB // Property 'prefixB' does not exist

const foo2: T2 = {
  a: "a",
  prefixB: {
    c: "obj"
  }
}
foo2.a // a
foo2.prefixB // { c: "obj" }
foo2.b // Property 'b' does not exist

const foo3: T2 = {
  a: "a",
  prefixB: {
    c: "obj"
  },
  b: {
    c: "obj"
  }
}
foo3.a // a
foo3.prefixB //  Property 'prefixB' does not exist
foo3.b // Property 'b' does not exist

【讨论】:

  • 嗨,不幸的是,您的解决方案是错误的,它仍然可能同意这两个值。对象时请试穿B
  • @user16195583 是的可能同意,但你不能使用它。
【解决方案2】:

我相信最简单的非通用方法是将T2 定义为:

type T2 = 
  | { a: string, b: B, prefixB?: never } 
  | { a: string, b?: never, prefixB: B }

playground link

【讨论】:

  • 好主意 - 效果很好,谢谢!我很好奇我们是否可以以某种方式简化:D。我正在填补我错过了 TS 的一些很酷的部分
  • 您可以实现某种通用帮助器来生成此类类型。但这肯定不会“更容易”。
猜你喜欢
  • 1970-01-01
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多