Closed
Description
TypeScript Version: 2.8.3 and next
Search Terms:
keyof inference
Code
export function Set<K extends string>(...keys: K[]): Record<K, true | undefined> {
const result = {} as Record<K, true | undefined>
keys.forEach(key => result[key] = true)
return result
}
export function keys<K extends string, V>(obj: Record<K, V>): K[] {
return Object.keys(obj) as K[]
}
type Obj = { code: LangCode }
/* No duplication - Derived */
const langCodeSet = Set('fr', 'en', 'es', 'it', 'nl')
export type LangCode = keyof typeof langCodeSet
export const langCodes = keys(langCodeSet)
// Does not compile (???)
const arr: Obj[] = langCodes.map(code => ({ code }))
/* Duplication */
export type LangCode2 = 'fr' | 'en' | 'es' | 'it' | 'nl'
export const langCodes2: LangCode2[] = ['fr', 'en', 'es', 'it', 'nl']
// Compiles
const arr2: Obj[] = langCodes2.map(code => ({ code }))
Expected behavior:
Everything should compile
Actual behavior:
Only the straightforward code compiles. The two are functionally equivalent.