使用 TypeScript,我可以输入 getProperty<T, K extends keyof T> 的柯里化版本吗

cha*_*lly 6 generics currying typescript

示例来自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]
}
Run Code Online (Sandbox Code Playgroud)

柯里化版本:

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)
Run Code Online (Sandbox Code Playgroud)

cha*_*lly 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]
  }
}
Run Code Online (Sandbox Code Playgroud)

看来打字更安全。

const getId = curriedGetProperty('id')
getId({id: 'foo'}) // returns string
getId({label: 'hello'}) // fails
Run Code Online (Sandbox Code Playgroud)