ts中interface中的条件类型

31 阅读1分钟

如果说ts在定义interface的时候,其中某个字段依赖于另一个字段怎么办

来看例子:

interface cartAction {
    type: "ADD" | "SUB" | "DELETE" | "EDIT" | "UPDATE_NAME";
    id: number;
    newName?: string;
}

newName依赖于UPDATE_NAME怎么办,就是说只有当type为UPDATE_NAME时才有newNAME

解决方案

使用联合类型来处理 newName

interface cartActionBase {
    id: number;
  }
  interface addAction extends cartActionBase {
    type: "ADD" | "SUB" | "DELETE" | "EDIT";
  }
  interface updateNameAction extends cartActionBase {
    type: "UPDATE_NAME";
    newName: string;
  }
  type cartAction = addAction | updateNameAction;