【发布时间】:2020-01-08 18:42:34
【问题描述】:
我无法为一个简单的函数编写正确的类型。
我想创建一个函数,当给定一个键 (keyof any) 或回调将返回另一个函数。这个函数接受一些数据并返回另一个键。
换句话说,toKey('propertyName') 和toKey(value => value.propertyName) 都会返回函数value => value.propertyName。当被调用时,只有当该属性的值是string、number 或symbol 类型时,该函数才会返回给定值。
这是一个例子:
function toKey(keyIdentity) { /* snippet */ }
interface IPerson {
firstName: string,
lastName: string,
age: number,
emails: string[]
};
const getKey1 = toKey((person: IPerson) => person.emails[0]);
const getKey2 = toKey('firstName');
const getKey3 = toKey('emails');
const person: IPerson = {
firstName: 'Craig',
lastName: 'Lipton',
age: 46,
emails: [
'<email-1>',
'<email-2>'
]
};
getKey1(person); // returns "<email-1>";
getKey2(person); // returns "Craig";
getKey3(person); // not allowed;
我尝试使用泛型和重载来实现正确的输入,但它很快就变得复杂了。
function toKey(key?: null): () => void;
function toKey<K extends keyof any>(key: K): <U extends keyof any>(item: Record<K, U>) => U;
function toKey<T extends (...args: any[]) => keyof any>(key: T): T;
function toKey(key: any): any {
if (isNil(key)) {
return noop;
}
return isFunction(key) ? key : (value: T) => value[key];
}
有没有更简单的方法来写这个?
【问题讨论】:
标签: typescript typescript-generics