2017-05-16 60 views
2

如何正確將其轉換爲單行?使用現有密鑰返回新對象的正確打字稿類型定義

我確實想從一個對象中獲取一個屬性,並返回一個只有該屬性的新對象。這是從對象過濾一些屬性:

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 & toObjExplicit

回答

0

toObjExplicit使用定義定義keystring這使編譯器很高興。

你可以做同樣的使用交集類型(K & string):

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

有趣的是崇高的插件,我用它來運行打字稿註釋告訴我,這是不行的「類型「{[X:字符串]:O型[K&string];}!== {[key:string]:O [K]}「 – Nox

+0

但是webpack不會抱怨......仍然不知道爲什麼這是 – Nox

+0

@Nox,[palyground](https ://www.typescriptlang.org/play/index.html#src=const%20select7%20%3D%20%3CO%2C%20K%20extends%20keyof%20O%3E(OBJ%3A%20O%2C%20prop %3A%20K%20%26%20string)%3A%20%7B%20%5Bkey%3A%20string%5D%3A%20O%5BK%5D%20%7D%20%3D%3E%20(%7B %20%5Bprop%5D%3A%20obj%5Bprop%5D%20%7D))。你使用什麼版本的打字稿? –

相關問題