如何对泛型参数使用类型断言

How can I use type assertion on generic parameters

假设我有这个代码:

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]) {}

这使我们能够正确地执行参数类型:

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

但是,当我在 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

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}]
  }
}

您可能已经注意到,您必须在条件之后而不是之前解构 const [key, value]...。否则,TS 无法将 key, value 与联合类型绑定。