正确的打字稿类型定义,用于返回具有现有键的新对象

时间:2017-05-16 13:00:11

标签: typescript type-definition

如何正确地将其转换为一行?

我确实希望从对象获取属性并返回仅具有该属性的新对象。这是从对象中过滤一些属性:

const pick = <O, K extends keyof O>(obj: O, prop: K) => obj[prop]
const toObj = <V>(key: string, value: V) => ({ [key]: value })
const select1 = <O, K extends keyof O>(obj: O, prop: K) => toObj(prop, pick(obj, prop))
// reduce some
const select2 = <O, K extends keyof O>(obj: O, prop: K) => toObj(prop, obj[prop])
// worked... now a on-liner?
const select3 = <O, K extends keyof O>(obj: O, prop: K) => ({ [prop]: obj[prop] })
// hmm... computed property must be string...
const select4 = <O, K extends keyof O>(obj: O, prop: string) => ({ [prop]: obj[prop] })
// huh? now: implizit any because type '{}'

// explicit version of toObj
// type is: { [key: string]: V }
const toObjExplicit = <V>(key: string, value: V): { [key: string]: V } => ({ [key]: value })
// test if that is okay
const select5 = <O, K extends keyof O>(obj: O, prop: K) => toObjExplicit(prop, obj[prop])
// yes, now combine
const select6 = <O, K extends keyof O>(obj: O, prop: K): { [key: string]: O[K] } => toObjExplicit(prop, obj[prop])
// works, try removing the toObj
const select7 = <O, K extends keyof O>(obj: O, prop: K): { [key: string]: O[K] } => ({ [prop]: obj[prop]})
// why...??? this should be identical, why do I need an extra function

问题是,为什么打字稿在我使用select7时无法使用该定义,而它与select6&amp; toObjExplicit

1 个答案:

答案 0 :(得分:0)

toObjExplicitkey定义为string,这使编译器感到满意。

您可以使用交集类型(K & string)执行相同操作:

const select7 = <O, K extends keyof O>(obj: O, prop: K & string): { [key: string]: O[K] } => ({ [prop]: obj[prop] })