打字稿检测类型

我想知道是否有一种方法可以解决ts错误,而无需添加和额外的宽松接口,或者将?的id设置为可选

所以一个例子是: 假设有这个基本界面

interface Task {
  id: string;
  label: string;
}

然后在代码中执行此操作

const task: Task = {
  label: "test"
}

Typescript Error here because it says that Task is missing ID.
          ↓
addTask(task);

...

const addTask = (task: Task) => {
  task.id = "1";
  ...
}

ts输出的错误是

Argument of type '{ label: string; }' is not assignable to parameter of type 'Task'.`

有没有办法告诉打字稿这不是问题,因为之后不久就会提供ID?

collinmao 回答:打字稿检测类型

您可以使用类型断言:

const task: Task = {
  label: "test"
} as Task
// Note the "as Task" at the end,or with different syntax:
const task: Task = <Task>{
  label: "test"
}

但是,如果以后仍然要添加ID,您也可以添加一个空ID来代替

const task: Task = {
  label: "test",id: ""
}

如果您的代码依赖于在创建任务之后并添加ID之前未设置ID,那么您应该使用?将其设置为可选,并正确处理。

,

我遇到了这个确切的问题,这就是我解决的方法:

type NewTask = Omit<Task,'id'>;

function addTask(newTask: NewTask): Task {

   // Do the thing,get an id variable

   return Object.assign({id},newTask);
}

Typescript不能很好地处理副作用,因此将此功能传递给不完整的版本并使其返回完整的版本是更有意义的……而不是就地编辑对象。

本文链接:https://www.f2er.com/3156604.html

大家都在问