interface INavigation {
children: string[];
initial: string;
}
function navigation({ children, initial }: INavigation) {
return null
}
我有一个类似于上面的函数。我正在尝试查看是否有办法将 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 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 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)
关于typescript - 根据 typescript 函数中的另一个参数限制一个参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73967239/