如何使用可选值定义接口,但其中一个是Mandatory - TypeScript

时间:2018-03-27 10:12:42

标签: typescript interface optional

如何定义具有少量可选值的TypeScript接口,但其中一个(或多个)强制 ???

假设我有以下代码:

interface ISearchKey
{
  name?: string;
  id?: number;
}

function findItem(search: ISearchKey): Item 
{
  // ... 

  return ...
}

我希望实现ISearchKey接口的对象具有“name”值和/或“id”值。可以发出其中一个(“name”和“id”),但不能同时发出两个!

我知道我可以通过验证findItem()函数中的输入来解决这个问题:

let name = search.name || "";
let id   = search.id   || -1;

或任何其他类型的输入验证,但是可以使用TypeScript 类型验证来完成吗?

1 个答案:

答案 0 :(得分:3)

联合类型,例如

type ISearchKey = { name: string } | { id: number }

const test = (key: ISearchKey) => console.log(key);

test({ name: "name" });
test({ id: 12 });
test({ name: "name", id: 12 });
test({ fail: true }); // Errors

对于必需的属性,您可以交叉:

// With mandatory data
type ISearchKey2 = ({ name: string } | { id: number }) & { data: any };

const test2 = (key: ISearchKey2) => console.log(key);

test2({ name: "name" }); // Error
test2({ name: "name", data: 0 });
test2({ id: 12 }); // Error
test2({ id: 12, data: 1 });
test2({ name: "name", id: 12 }); // Error
test2({ name: "name", id: 12, data: 2 });
test2({ fail: true }); // Still Errors

正如 @jcalz 所指出的那样,这些联合允许对其他属性进行不同的输入,只要其中一个属性存在,例如。

{ name: "name", id: "not a number!" }

更正确的类型联合将是:

{name: string, id?: number} | {name?: string, id: number}

这将保留正确类型的可选属性。