相关疑难解决方法(0)

获取字典/对象键作为打字稿中的元组

我想从TS 3.1中的对象获取具有正确类型文字的正确元组类型:

interface Person {
  name: string,
  age: number
}

// $ExpectType ['name','age']
type ObjectKeysTuple = ToTuple<keyof Person>
Run Code Online (Sandbox Code Playgroud)

为什么?:

使用时获取正确的字符串文字元组 Object.keys(dictionary)

随着keyof工会的扩大,我无法找到解决方案,这('name' | 'age')[]肯定不是我们想要的。

type ObjectKeysTuple<T extends object> = [...Array<keyof T>]
type Test = ObjectKeysTuple<Person>
// no errors not good
const test: Test = ['age','name','name','name']
Run Code Online (Sandbox Code Playgroud)

有关:

tuples unions typescript

2
推荐指数
3
解决办法
995
查看次数

标签 统计

tuples ×1

typescript ×1

unions ×1