小编cha*_*lly的帖子

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

示例来自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)

generics currying typescript

6
推荐指数
1
解决办法
316
查看次数

标签 统计

currying ×1

generics ×1

typescript ×1