![](/img/trans.png)
[英]How to define array typescript interface with optional unique strings?
[英]How define an Interface with Optional values, but one of them Mandatory - TypeScript
如何定义具有一些可选值的TypeScript接口,但其中一个(或多个)是强制性的 ?
假设我有以下代码:
interface ISearchKey
{
name?: string;
id?: number;
}
function findItem(search: ISearchKey): Item
{
// ...
return ...
}
并且我希望实现ISearchKey
接口的对象具有“名称”值和/或“ id”值。 可以发出其中一个(“名称”和“ id”),但不能同时发出!
我知道我可以通过验证findItem()
函数中的输入来解决此问题:
let name = search.name || "";
let id = search.id || -1;
或任何其他类型的输入验证,但是可以使用TypeScript 类型验证吗?
合并类型,例如
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}
这将保留正确类型的可选属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.