Home > Enterprise >  Typescript tuple function arguments based on key
Typescript tuple function arguments based on key

Time:12-16

I'm writing types for my api which is based on tuples. I'm trying to infer the arguments of the function in this tuple.

For the sake of simplicity I've made a small example of what I'm roughly trying to achieve.

type InitType = ['init', (arg: string) => void]
type DestroyType = ['destroy', (arg: number) => void]
type GetType = ['get', () => void]

type Expected = InitType | DestroyType | GetType

// Expecting arg to be of type string
const test: Expected = ['init', (arg) => {
    console.log(arg)
}]

// Expecting arg to be of type number?
const test1: Expected = ['destroy', (arg) => {
    console.log(arg)
}]

// This does get checked tho..
const test2: Expected = ['get', () => {
    console.log(arg)
}]

CodePudding user response:

As of December 2022, autocompletion for discriminated union of tuples is less powerful than for discriminated union of objects.

Compare with object-based union:

type InitType = {name: 'init', fn: (arg: string) => void}
type DestroyType = {name: 'destroy', fn: (arg: number) => void}
type GetType = {name: 'get', fn: () => void}

type Expected = InitType | DestroyType | GetType

// arg is string
const test: Expected = {name: 'init', fn: (arg) => {
    console.log(arg)
}}

// arg is number
const test1: Expected = {name: 'destroy', fn: (arg) => {
    console.log(arg)
}}

// arg is noit available
const test2: Expected = {name: 'get', fn: () => {
    console.log(arg) // Expected error
}}

There is an open issue addressing precisely your scenario better autocompletion for dicriminated union as tuples #31977

  • Related