【问题标题】:Why Typescript sometimes doesn't allow to set value if it's structurally compatible with the type?如果 Typescript 在结构上与类型兼容,为什么有时不允许设置值?
【发布时间】:2022-01-09 01:39:54
【问题描述】:

TypeScript 使用结构类型,这很好,但我注意到它有时会在结构上没有差异时抱怨。为什么会这样?这是怎么回事?

例子:

enum TagType {
    SIMPLE = 'simple',
    COLLECTOR = 'collector',
}

interface CollectorTag {
    type: TagType.COLLECTOR,
}

const tag1_1: CollectorTag = {
  type: TagType.COLLECTOR,
};

const tag1_2 = tag1_1;


const tag2_1 = {
  type: TagType.COLLECTOR,
};

const tag2_2: CollectorTag = tag2_1;
      ^^^^^^
      Error here

Playground Link

【问题讨论】:

  • tag2_1 的类型被编译器推断为{ type: TagType; },所以如果你以后想的话,你可以写tag2_1.type = TagType.SIMPLE。所以那个类型和CollectorTag是不同的,你不能把前者分配给后者。它没有意识到您的意图是type 属性应该始终TagType.COLLECTOR。要传达该意图,您可以使用const 断言,如this,并且一切正常。如果这是有道理的,我可以写一个答案;否则,请详细说明您缺少什么。
  • 或者@TitianCernicovaDragomir 可以做到吗????

标签: typescript typescript-typings


【解决方案1】:

因为这些类型并不真正兼容tag2_1.tag 可以是任何TagType,而tag1_1.tag 是枚举TagType.COLLECTOR 的特定值。

文字值类型存在于打字稿中,这意味着一个值可以作为一种类型,并且只有特定的值可以分配给这种文字值类型。它们通常对联合有用

使用 as const 将使 typescript 也将 tag2_1.tag 推断为文字类型


const tag2_1 = {
  type: TagType.COLLECTOR,
} as const;
const tag2_2: CollectorTag = tag2_1;

Playground Link

【讨论】:

  • 谢谢!这感觉像是一个棘手的问题,可以在面试中用来迷惑候选人哈哈。
猜你喜欢
  • 1970-01-01
  • 2019-08-06
  • 2013-03-03
  • 1970-01-01
  • 2020-06-30
  • 2017-10-11
  • 2021-04-19
  • 2022-01-22
相关资源
最近更新 更多