获取混合类型数组每个索引的元素类型

Ale*_*oti 4 typescript

我有一个混合数组,如:

const array = [false, 1, '', class T {}];
Run Code Online (Sandbox Code Playgroud)

谁的类型是:

type arrayType = typeof array; // (string | number | boolean | typeof T) []
Run Code Online (Sandbox Code Playgroud)

并且任何索引中的对象类型是:

string | number | boolean | typeof T
Run Code Online (Sandbox Code Playgroud)

如何从特定索引获取对象的类型,如下所示,而不是类型的联合?

const a = array [0] // should be boolean
const b = array [1] // should be number
const c = array [2] // should be string
const d = array [3] // should be typeof T
Run Code Online (Sandbox Code Playgroud)

TS游乐场

Tit*_*mir 5

您需要使用元组类型。您可以明确说明类型,也可以使用as const断言使 TS 推断出元组类型:

const array = [false,1,''] as const;


type arrayType = typeof array; /// readonly [false, 1, ""]

Run Code Online (Sandbox Code Playgroud)

游乐场链接

  • @MuratKaragöz,它是 TS 编译器改变推理方式的标记,即,它将保留文字类型,它将保留元组,并且将使元组只读 https://github.com/Microsoft/TypeScript/拉/29510 (2认同)