gpt4 book ai didi

typescript - TypeScript 中类和对象文字之间的类型检查

转载 作者:行者123 更新时间:2023-12-04 17:40:37 24 4
gpt4 key购买 nike

在 TypeScript 中,如果对象提供类所需的所有属性和方法,则可以将对象文字分配给类类型变量。

class MyClass {
a: number;
b: string;
}

// Compiler won't complain
const instance: MyClass = { a: 1, b: '' };

// Compiler won't complain if I assign an object with more properties
const literal = { a: 1, b: '', c: false };
const instance2: MyClass = literal;

我想在这里做的是基于两个原因来防止这种赋值:

  1. 实例 instanceof MyClass 应该为真;
  2. 我可以为对象分配更多属性(见上文)。

这样一来,TypeScript 类就更像一个接口(interface)了。有什么办法可以防止这种情况发生吗?

最佳答案

来自 the TypeScript docs ,您所观察到的似乎是预期的行为:

Type compatibility in TypeScript is based on structural subtyping. Structural typing is a way of relating types based solely on their members.

因此,如果两个类型具有相同的结构,则意味着这些类型的对象可以相互赋值。

解决方法:私有(private)成员

一旦您开始向类添加私有(private)成员(您在实践中几乎总是这样做),类型检查的工作方式就更接近于您想要的方式。

class MyClass {
a: number;
b: string;
private c: number;
}

// "Property 'c' is missing in type '{ a: number; b: string; }' but required in type 'MyClass'."
const instance: MyClass = { a: 1, b: '' };

// "Property 'c' is private in type 'MyClass' but not in type '{ a: number; b: string; c: number; }'"
const literal: MyClass = { a: 1, b: '', c: 3 };

class OtherClass {
a: number;
b: string;
private c: number;
}

// "Types have separate declarations of a private property 'c'"
const otherClass: MyClass = new OtherClass();

关于typescript - TypeScript 中类和对象文字之间的类型检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54645400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com