javascript - 流类型: How to create an instance of an exact type from a class

标签 javascript flowtype

我有以下类型和类:

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 并添加了一个附加属性。因为类是名义上类型化的,所以 BarFoo 的子类型。因此,Foo 不能是 {| 的子类型foo: string |} 而不破坏类型系统。

创建精确对象的推荐方法是只编写对象文字,就像我在本例中为 z 所做的那样。

关于javascript - 流类型: How to create an instance of an exact type from a class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59578017/

相关文章:

Javascript:复制变量和原型(prototype)

javascript - 处理多个 promise 和回调时混淆流错误

javascript - 调用 `this.setState()` 会中断对 componentWillReceiveProps 中的 prop 进行流类型检查

javascript - Angular ui-leaflet Map, map 下的卫星混合选项?

javascript - 如何使用 Node 自定义此构建脚本?

javascript - Backbone JS : Can you change templates of a view on the fly?

javascript - 无法有条件地设置react中span的样式集(css模块)

javascript - flowtype - 函数参数只能是对象的属性值之一

javascript - 什么是 "types first"流架构?

javascript - 查找流量错误的根源