【问题标题】:I want to union two objects in other way我想以其他方式合并两个对象
【发布时间】:2022-01-16 16:23:18
【问题描述】:

我想按照我的想法合并两个对象,但是typescript似乎只有一种合并对象的方法

type A = {
  m: string;
  n: number;
}

type B = {
 n: string;
}

type C = B | A;

C 的结果类型是这样的

{
  m: string;
  n: number | string;
}

但我想要的是 A 只能代表分歧

//i want it is inValid
{
  m: "hello",
  n: "hi"
}
//other case is valid
{
  m: "hello",
  n: 1
}
{
  n: "hello"
}

【问题讨论】:

标签: typescript types


【解决方案1】:

以上问题可以这样解决

type A = {
  a: string;
  b?: string;
}
type C = {
  a?: undefined;
  b: number;
}

但是下面还是没有解决

type A = {
  a: string;
  b?: string;
}

type B = {
  a: number;
  b?: number;
}

type C = {
  a?: undefined;
  b: number;
}

type P = A | B | C;

我想要的P的类型是严格联合,当a没有值时,b必须是数字,当a是数字时,b可以是数字或不存在,当a是字符串时,b可以是字符串或不存在存在

【讨论】:

  • 我自己弄糊涂了,这种方式可以涵盖所有情况
猜你喜欢
  • 2010-11-14
  • 2020-03-22
  • 2016-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-17
  • 2013-11-26
  • 2011-08-16
相关资源
最近更新 更多