[英]TypeScript: Restrict function parameter value to values of array within dynamic variable
我有一個返回 function 的簡單反應鈎子。我希望這個 function 只接受傳遞給鈎子的數組中的值。
這是鈎子:
type Options<P> = {
pathname: string;
rootPath: string;
paths: P;
};
export const useLayoutPaths = <P extends string[]>(options: Options<P>) => {
const { pathname, rootPath, paths } = options;
if (paths.length === 0) {
throw new Error("paths must be a non-empty array.");
}
const currentPath = pathname.substring(pathname.lastIndexOf("/") + 1);
const value = paths.includes(currentPath) ? currentPath : paths[0];
const getPath = (name: typeof paths[number]): string =>
`${rootPath}/${String(name)}`;
return { value, getPath };
};
我希望 getPath function 只允許存在於“路徑”變量中的值。
這是我目前的用法:
const { value, getPath } = useLayoutPaths({
pathname,
rootPath: `/department/${orgId}`,
paths: ["trends", "comments"],
});
console.log(getPath("trends")) <-- Only allow "trends" or "comments"
您希望編譯器跟蹤作為paths
屬性傳入的字符串的文字類型。 不幸的是,對於像P extends string[]
這樣的通用約束,這並沒有發生。 增加編譯器將"foo"
視為"foo"
類型而不是string
類型的可能性的一種方法是將泛型類型參數限制為string
。 所以P extends string
會更好用。 我們可以讓P
成為paths
元素的類型而不是paths
本身,如下所示:
export const useLayoutPaths = <P extends string>(options: Options<P[]>) => {
// impl
};
這將按需要工作,但編譯器不喜歡讓您在P
的數組中查找string
。 有關詳細信息,請參閱此問答。 處理這個問題的最簡單方法是在使用includes()
之前將paths
從P[]
擴展到readonly string[]
:
export const useLayoutPaths = <P extends string>(options: Options<P[]>) => {
const { pathname, rootPath, paths } = options;
if (paths.length === 0) {
throw new Error("paths must be a non-empty array.");
}
const currentPath = pathname.substring(pathname.lastIndexOf("/") + 1);
const value = (paths as readonly string[]).includes(currentPath) ? currentPath : paths[0];
const getPath = (name: typeof paths[number]): string =>
`${rootPath}/${String(name)}`;
return { value, getPath };
};
現在一切如你所願:
console.log(getPath("trends")) // okay
getPath("oops"); // error!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.