Basic mapped tuple type example?

Viewed 92
1 Answers

The trick is to convert over a generic type parameter not a specific type!

type Original = [number, string, Date]
type Converter<T> = T | undefined

type ConvertArray<T> = { [K in keyof T]: Converter<T[K]> }
type Final = ConvertArray<Original>


const fine: Final = [1, 'a', undefined]
const causesError: Final = ['a', 'a', 'a']
const alsoFine = fine.map(val => val)
const doubleLength = fine.length * 2
function fineFunc([num, str, date]: Final) {}
fineFunc(fine)
fineFunc(['a', 'a', 'a']) // error (correctly)

// If you don't use the generic intermediate step:
type WrongFinal = { [K in keyof Original]: Converter<Original[K]>}
const seemsOkRight: WrongFinal = [1, 'a', new Date()]
const actuallyWontWork = seemsOkRight.length * 2 // <- Error!!

Playground

Related