我有一個回傳函式的簡單反應鉤子。我希望這個函式只接受來自傳遞給鉤子的陣列的值。
這是鉤子:
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 函式只允許存在于“paths”變數中的值。
這是我目前的用法:
const { value, getPath } = useLayoutPaths({
pathname,
rootPath: `/department/${orgId}`,
paths: ["trends", "comments"],
});
console.log(getPath("trends")) <-- Only allow "trends" or "comments"
uj5u.com熱心網友回復:
您希望編譯器跟蹤作為屬性傳入的字串的文字型別。paths不幸的是,這并沒有發生在像P extends string[]. 增加編譯器將"foo"其視為型別"foo"而不是型別的可能性的一種方法string是將泛型型別引數約束為string. 所以P extends string會更好地作業。我們可以只是P元素的型別paths而不是paths它本身,像這樣:
export const useLayoutPaths = <P extends string>(options: Options<P[]>) => {
// impl
};
這將按需要作業,但編譯器不喜歡讓您string在P. 有關更多資訊,請參閱此問題和答案。處理這個問題的最簡單方法是在使用之前paths從P[]to擴大:readonly string[]includes()
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!
Playground 代碼鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/490046.html
下一篇:打字稿錯誤:型別'{道具:IDrink;}'不可分配給型別'IntrinsicAttributes&IDrink'
