如何仅从接口联合中的一种类型继承属性

问题描述 投票:0回答:1

如何使对象x具有仅来自ABC之一的属性。当前,它可以具有所有属性abc,我只希望它成为其中一个,而没有另一个。

interface A {
  a: string;
}
interface B {
  b: string;
}
interface C {
  c: string;
}

type X = A | B | C;

const x: X = {
  a: 'a',
  b: 'b',
  c: 'c'
};

console.log(x); // returns { a: "a", b: "b", c: "c" }, should throw error.

打字稿版本-3.8.3

typescript interface union
1个回答
0
投票

查看TypeScript文档(here),我不确定使用接口是否可行(我很可能错了)。但是我确实设法实现了使用Enums所需要的功能。

enum A {
  a = 'a'
}
enum B {
  b = 'b'
}
enum C {
  c = 'c'
}

type X = A | B | C;

const x: X = {
  a: 'a',
  b: 'b',
  c: 'c'
};
/* This does throw an error:
Type '{ a: string; b: string; c: string; }' is not assignable to type 'X'.
  Type '{ a: string; b: string; c: string; }' is not assignable to type 'C'.
© www.soinside.com 2019 - 2024. All rights reserved.