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

问题描述

假设我有这个代码

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 与联合类型绑定。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...