3

[求助] typescript 的嵌套类型检查问题

 1 year ago
source link: https://www.v2ex.com/t/860507
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  程序员

[求助] typescript 的嵌套类型检查问题

  yodhcn · yodhcn · 5 小时 39 分钟前 · 423 次点击

如下面的代码所示,我声明了一个名为 Test 类型,其中一个 key 为 abc 的 value 类型为 ABC 。
[问题]
Typescript 只会检查 Test.abc 里面的 key 类型是否正确,以及是否缺少 key ,但不会检查是否有多余的 key 。
为啥会出现这种情况?以及如何解决嵌套类型验证的问题?

// 声明一个名为 ABC 的类型
export type ABC = {
  a: string;
  b: number;
  c: string;
};

// 声明一个名为 Test 类型,其中一个 key 为 abc 的 value 类型为 ABC
export type Test = {
  a: string;
  b: number;
  c: string;
  abc: ABC;
};

// 对象 abc
const abc: ABC = {
  a: 'aaa',
  b: 111,
  c: 'ccc',
};

// 对象 abcd
const abcd = {
  a: 'aaa',
  b: 111,
  c: 'ccc',
  d: 'ddd',
};

// 对象 ab
const ab = {
  a: 'aaa',
  b: 111,
};

// 对象 abc 通过类型检查
const test_1: Test = {
  a: 'aaa',
  b: 111,
  c: 'ccc',
  abc: abc,
};
console.log(test_1);

// 对象 abcd 通过类型检查
const test_2: Test = {
  a: 'aaa',
  b: 111,
  c: 'ccc',
  abc: abcd,
};
console.log(test_2);

// 对象 ab 没有通过类型检查
const test_3: Test = {
  a: 'aaa',
  b: 111,
  c: 'ccc',
  abc: ab,
};
console.log(test_3);

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK