来自https://www.typescriptlang.org/docs/handbook/advanced-types.html
的示例function getProperty<T, K extends keyof T>(o: T, name: K): T[K] {
return o[name]; // o[name] is of type T[K]
}
咖喱版:
function curriedGetProperty<T, K extends keyof T>(name: K): (o: T) => T[K] {
return (o: T) => o[name]; // o[name] is of type T[K]
}
const record = { id: 4, label: 'hello' }
const getId = curriedGetProperty('id') // Argument of type '"id"' is not assignable to parameter of type 'never'.
const id = getId(record)
答案 0 :(得分:1)
const getProperty = <P extends string>(prop: P) => <O extends any>(obj: O) => obj[prop]
const record = { id: 4, label: 'hello' }
const getId = getProperty('id')
const id = getId(record)
这似乎有效。 id
的类型被正确推断为数字。如果传入any
的对象上没有getId
属性,那么您只会收到id
,所以它并不严格,但是一个整体优雅的解决方案。
编辑:自写这个答案以来,我已经了解到Record
类型可用于指定需要特定键的对象类型。利用这些知识,我们可以编写一个类型安全,简洁,可读的解决方案:
// implementation
const get = <K extends string>(key: K) => <V>(obj: Record<K, V>) => obj[key]
// usage
const person = {
name: "kingdaro",
age: 21,
}
const fruit = {
type: "apple",
color: "red",
}
const nameGetter = get("name")
nameGetter(person) // return type inferred as string
nameGetter(fruit) // fails, fruit has no key "name"
// minor caveat: when passing an object literal, the extra key will raise an error
// you can declare the object separately to sidestep around this
// but this wouldn't come up often anyway
nameGetter({ name: "kingdaro", age: 21 })
答案 1 :(得分:1)
如果将其分为两个步骤,则可以同时具有最小的冗长和完全类型安全性:
interface recordType {
id: number,
label: string
}
const record = { id: 4, label: 'hello' };
const getPropertyBuilder = function <T>() {
return <K extends keyof T>(key: K) => (o: T) => o[key];
};
const propertyBuilder = getPropertyBuilder<recordType>();
const getId = propertyBuilder('id'); // getId is (o: recordType) => number
const id = getId(record); // id is number
// or in one go
const label = getPropertyBuilder<recordType>()('label')(record); // label is string
如上所述,也适用于Partial
:
const propertyBuilder = getPropertyBuilder<Partial<typeof record>>();
const getId = propertyBuilder('id');
const id = getId(record); // id is number
const id2 = getId({ id: 3 }); // also number
答案 2 :(得分:1)
type WithProp<T extends any, K extends string> = { [P in K]: T[P] }
function curriedGetProperty <P extends string>(prop: P) {
return <T, O extends WithProp<T, typeof prop>>(o: O) => {
return o[prop]
}
}
似乎输入更安全。
const getId = curriedGetProperty('id')
getId({id: 'foo'}) // returns string
getId({label: 'hello'}) // fails
答案 3 :(得分:0)
使用TypeScript 3.0.3
能够做到这一点:
function composeGetter<K extends string>(prop: K) {
function getter<T extends { [P in K]?: any }>(object: T): T[typeof prop]
function getter<T extends { [P in K]: any }>(object: T) {
return object[prop]
}
return getter
}