【问题标题】:Understanding typescript structual typesystem理解 typescript 结构类型系统
【发布时间】:2021-12-14 11:08:01
【问题描述】:

为什么这个例子在 Typescript 中没问题:

class Person {
    name: String;
    age: number;
}

class Customer {
    name: String;
}

const cust: Customer = new Person();

但不是这个例子?

type Boj = {boj: number};
let b: Boj = {boj: 3, jj: 3};

不应该都使用结构类型系统吗?

【问题讨论】:

  • 你告诉 TS b 的类型是 BojBoj 没有 jj 属性,所以你不能分配它……这就是 TypeScript 的重点:类型安全。如果你想分配属性而不考虑类型,请使用any 或不使用 TypeScript。
  • @Cerbrus,实际上这是 Typescript 检查额外属性的特殊情况。只有对象字面量有多余的属性检查,否则允许额外的属性。

标签: typescript types


【解决方案1】:

第二个示例中的行为称为 excess property checking

TypeScript 的立场是,这段代码可能存在错误。对象文字在将它们分配给其他变量或将它们作为参数传递时会得到特殊处理并进行过多的属性检查。如果一个对象字面量有任何“目标类型”没有的属性,你会得到一个错误

应用于对象字面量。仍然允许分配具有额外属性的变量:

type Boj = { boj: number };

const foo = { boj: 3, jj: 3 }; // inferred type is { boj: number; jj: number; }
let b: Boj = foo; // no error here, foo is not object literal

【讨论】:

猜你喜欢
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2011-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多