2017-05-16 5 views
2

Comment convertir correctement cette ligne en une seule ligne?définition de type tapuscrit correcte pour renvoyer un nouvel objet avec une clé existante

Je souhaite extraire une propriété d'un objet et retourner un nouvel objet avec juste cette propriété. Ceci est de filtrer certaines propriétés d'un objet:

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 

La question est, pourquoi est-tapuscrit incapable d'utiliser la définition quand je l'utilise select7, alors qu'il est identique à select6 & toObjExplicit

Répondre

0

toObjExplicit définit key comme string ce qui rend le compilateur heureux.

Vous pouvez faire la même chose en utilisant le type d'intersection (K & string):

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

Fait intéressant le plugin sublime que j'utilise pour exécuter les annotations dactylographiées me dit que ce n'est pas correct « Type « {[x: string]: O [K & string];}! == {[clé: chaîne]: O [K]} " – Nox

+0

Mais webpack ne se plaint pas ... encore pas sûr pourquoi c'est – Nox

+0

@Nox, pas d'erreurs dans [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% 20surface% 5D% 3A% 20O% 5BK% 5D% 20% 7D% 20% 3D% 3E% 20 (% 7B % 20% 5Bprop% 5D% 3A% 20obj% 5Bprop% 5D% 20% 7D)). Quelle version de tapuscrit utilisez-vous? –