如何根据工厂参数键入一个钩子工厂
How to type an hooks factory based on factory parameter
在 Typescript 中,是否可以创建一个 return 函数的工厂,该函数作为基于完全类型化的工厂参数的名称?
像这样:
type ReturnType<T extends string> = {
[key in `use${T}`]: () => void;
};
const hookFactory = <T extends string>(name: string): ReturnType<T> => { // Need to pass "name" value
const hookName = `use${name.charAt(0).toUpperCase() + name.slice(1)}`;
return {
[hookName]: () => {
console.log("working")
}
};
}
并像这样使用它:
const { useTest } = hookFactory('test');
示例有效,但未输入。不得不猜钩子名字是对象解构
我知道怎么做了:
type FactoryReturnType<T extends string> = {
[key in `use${Capitalize<T>}`]: () => void;
};
function hookFactory<T extends string>(name: T): FactoryReturnType<T> {
const hookName = `use${name.charAt(0).toUpperCase() + name.slice(1)}`;
return {
[hookName]: () => {
console.log("working")
}
} as FactoryReturnType<T>;
}
const { useTest } = hookFactory('test'); // OK
const { useTest } = hookFactory('testx'); // not OK
在 Typescript 中,是否可以创建一个 return 函数的工厂,该函数作为基于完全类型化的工厂参数的名称?
像这样:
type ReturnType<T extends string> = {
[key in `use${T}`]: () => void;
};
const hookFactory = <T extends string>(name: string): ReturnType<T> => { // Need to pass "name" value
const hookName = `use${name.charAt(0).toUpperCase() + name.slice(1)}`;
return {
[hookName]: () => {
console.log("working")
}
};
}
并像这样使用它:
const { useTest } = hookFactory('test');
示例有效,但未输入。不得不猜钩子名字是对象解构
我知道怎么做了:
type FactoryReturnType<T extends string> = {
[key in `use${Capitalize<T>}`]: () => void;
};
function hookFactory<T extends string>(name: T): FactoryReturnType<T> {
const hookName = `use${name.charAt(0).toUpperCase() + name.slice(1)}`;
return {
[hookName]: () => {
console.log("working")
}
} as FactoryReturnType<T>;
}
const { useTest } = hookFactory('test'); // OK
const { useTest } = hookFactory('testx'); // not OK