示例来自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)
编辑 TypeScript >= 4.1.5
const makeGetter = <TKey extends string>(key: TKey) => <TObject extends { [P in TKey]?: unknown }>(object: TKey extends keyof TObject ? TObject : `${TKey} is missing as property of object`) => (object as TObject)[key];
const getId = makeGetter('id');
const a: unknown = getId({})
const b: number = getId({id: 1})
const c: number | undefined = getId({} as { id?: number})
编译器会抱怨getId({})
并附有有用的错误消息。
使用 TypeScript3.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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)