我有以下类型和类:
export type ProductType = {|
id: number,
name: string,
slug: string,
tooltip: string,
properties?: string[]
|};
class Product {
id: number,
name: string,
slug: string,
tooltip: string,
properties?: string[]
constructor(props: $Shape<ProductType>) {
this.id = props.id;
this.name = props.name || '';
this.slug = props.slug || '';
this.tooltip = props.tooltip || '';
this.properties = props.properties || [];
}
}
我希望能够做这样的事情:
const product: ProductType = new Product({ name: 'test' });
但是流提示说以下内容:
Cannot assign `new Product()` to `product` because inexact `Product` [1] is incompatible with exact `ProductType`
所以我想知道是否有任何方法可以从类构造函数返回精确/卡住/密封对象,或者这是否可能,如果不可能,我还有什么其他选择。
最佳答案
不幸的是,类实例是不精确的。这是一个例子:
class Foo {
foo: string;
constructor() {
this.foo = 'foo';
}
}
class Bar extends Foo {
bar: string;
constructor() {
super();
this.bar = 'bar';
}
}
type JustFoo = {| foo: string |};
const x: Foo = new Bar();
// Expected error -- if Flow allowed this, the exact type would be a lie!
const y: JustFoo = x;
const z: JustFoo = { foo: "foo" };
( playground )
在本例中,Bar
扩展了 Foo
并添加了一个附加属性。因为类是名义上类型化的,所以 Bar
是 Foo
的子类型。因此,Foo
不能是 {| 的子类型foo: string |}
而不破坏类型系统。
创建精确对象的推荐方法是只编写对象文字,就像我在本例中为 z
所做的那样。
关于javascript - 流类型: How to create an instance of an exact type from a class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59578017/