小编Ern*_*cki的帖子

Flowtype扩展对象类型

作为JavaScript开发人员,我是新手进行类型检查,我很难理解为什么这个简单的代码不起作用:

type Animal = {
  id: number,
  name: string,
  type: 'dog' | 'cat'
};

type Dog = {
  id: number,
  name: string,
  type: 'dog',
  color: string
};

function printAnimal(animal: Animal): string {
  return `${animal.type}: ${animal.name}`;
}

const buddy: Dog = {
  id: 1,
  name: 'Buddy',
  type: 'dog',
  color: 'black'
}

printAnimal(buddy);
Run Code Online (Sandbox Code Playgroud)

我在这里想要实现的是拥有一个接受接口的方法.然而这给了我错误:Cannot call 'printAnimal' with 'buddy' bound to 'animal' because string literal 'dog' [1] is incompatible with string literal 'cat' [2] in property 'type'..

我尝试了什么:

  1. interface Animal { …

javascript flowtype

5
推荐指数
1
解决办法
109
查看次数

标签 统计

flowtype ×1

javascript ×1