我一直在寻找omit()只使用 JavaScript 的Lodash 替代品。这就是我想要实现的目标:
function omit(obj, attr) {
// @obj: original object
// @attr: string, attribute I want to omit
// return a new object, do not modify the original object
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经找到了这个解决方案:
let { attr, ...newObj } = obj;
Run Code Online (Sandbox Code Playgroud)
但它只有在attr已知时才有效。我想attr是动态的,所以attr应该是一个字符串。我该怎么做?
如何为动态创建的函数声明泛型类型?
type FooType = {
username: string;
}
type BarType = {
age: number;
}
interface DataStore {
foo: FooType;
bar: BarType;
}
const getDataStore = () => ({
foo: { username: 'Tera' },
bar: { age: 24 },
})
const generateFunction = <T, S extends keyof DataStore>(slice: S) => {
type DataSlice = DataStore[S];
return (selector: (store: DataSlice) => T) => selector(getDataStore()?.[slice]);
}
Run Code Online (Sandbox Code Playgroud)
如何使用TinuseFoo和 pass generateFunction?
const useFoo = generateFunction('foo');
Run Code Online (Sandbox Code Playgroud)
预期使用量useFoo
type UserName …Run Code Online (Sandbox Code Playgroud)