[英]limit the type of one argument based on anther argument in typescript function
interface INavigation {
children: string[];
initial: string;
}
function navigation({ children, initial }: INavigation) {
return null
}
我有一个 function 看起来像上面的东西。 我正在尝试查看是否有办法将initial
输入限制为仅来自children
数组的列表。
例如,
// should work
navigation({ children: ["one", "two", "three"], initial: "one" })
navigation({ children: ["one", "two", "three"], initial: "two" })
// should throw a type error
// Type 'four' is not assignable to type 'one' | 'two' | 'three'.
navigation({ children: ["one", "two", "three"], initial: "four" })
有没有办法使用 typescript 来做到这一点?
我只能想到在 function 中抛出一个错误
function navigation({ children, initial }: INavigation) {
if (!children.includes(initial)) {
throw new Error(`${initial} is invalid. Must be one of ${children.join(',')}.`
}
return null
}
您需要使您的INavigation
类型通用,以便它可以捕获一些特定的字符串集。
interface INavigation<Children extends readonly string[]> {
children: Children;
initial: Children[number];
}
这里的Children
是某种字符串的数组,并被指定为children
属性的类型。 initial
是该数组的成员类型。
然后使您的 function 通用以提供该类型:
function navigation<Children extends readonly string[]>(
{ children, initial }: INavigation<Children>
) {
return null
}
然后将as const
添加到您的示例数据中,以确保将它们推断为字符串文字类型,而不仅仅是string
。
// should work
navigation({ children: ["one", "two", "three"], initial: "one" } as const)
navigation({ children: ["one", "two", "three"], initial: "two" } as const)
// should throw a type error
// Type 'four' is not assignable to type 'one' | 'two' | 'three'.
navigation({ children: ["one", "two", "three"], initial: "four" } as const)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.