typescript 获取对象的值的并集

izkcnapc  于 2023-05-23  发布在  TypeScript
关注(0)|答案(1)|浏览(167)

我正在尝试为一个函数编写类型,该函数接受任何结构的记录,并将值转换为可区分的并集。下面是一些例子:

const getKeys = <T extends {key: string}>(items: T[]): T['key'] => {
    // ...
}

// keys should have type "foo" | "bar"
// instead has type string
const keys = getKeys([{ key: "foo" }, { key: "bar" }])

// keys2 should have type "baz" | "qux"
// instead has type string
const keys2 = getKeys([{ key: "foo" }, { key: "qux" }])

但是,keyskeys2的类型为string
理想情况下,你会得到像下面这样的好API,工作示例,但使用记录:

const getKeys = <T extends string>(items: T[]): T => {
    // ...
}

// keys has type "foo" | "bar"
const keys = getKeys(["foo", "bar"])

// keys2 has type "baz" | "qux"
const keys2 = getKeys(["baz", "qux"])

我该怎么做?

需求

  • 无法对参数使用as const
oalqel3c

oalqel3c1#

constAssert的替代方法是Typescript 5.0中引入的const类型参数。
以前,typescript会为对象推断一个更通用的类型;但是,const type assertions告诉编译器采用确切的类型,而不是使其更通用。
实施:

const getKeys = <const T extends { key: string }>(items: T[]): T['key'] => {
  return {} as any
};

// keys should have type "foo" | "bar"
const keys = getKeys([{ key: 'foo' }, { key: 'bar' }]);

// keys2 "baz" | "qux"
const keys2 = getKeys([{ key: 'bar' }, { key: 'qux' }]);

Playground

相关问题