Search code examples
typescriptgeneric-type-parameters

How can I use type assertion on generic parameters


Suppose I have this code:

const items = {
  A: { x: 0 },
  B: { y: 0 },
  C: { z: 0 },
}
type Items = typeof items;

function foo<K extends keyof Items>(key: K, value: Items[K]) {}

This allows us to correctly enforce the type of parameters:

foo('A', { x: 0 }) // good
foo('A', { y: 0 }) // error

But how can I "assert" the type of generic parameter (or how to use some kind of type guard) when I'm inside foo?

function foo<K extends keyof Items>(key: K, value: Items[K]) {
  if (key === 'A') {
    // theoretically, if K is 'A', then Items[K] must be { x: 0 }
    const bar = value.x // But actually, it's error
  }
}

Playground


Solution

  • const items = {
      A: { x: 0 },
      B: { y: 0 },
      C: { z: 0 },
    }
    type Items = typeof items;
    
    type Values<T> = T[keyof T]
    
    type Union = {
      [P in keyof Items]: [P, Items[P]]
    }
    
    
    function foo(...args: Values<Union>) {
      if (args[0] === 'A') {
        const [key,value] = args // [A, {x: number}]
      }
    }
    

    As you might have noticed, you have to destructure const [key, value]... after condition, not before. Otherwise, TS is unable to bind key, value with the union type.