我有一个混合数组,如:
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)
您需要使用元组类型。您可以明确说明类型,也可以使用as const断言使 TS 推断出元组类型:
const array = [false,1,''] as const;
type arrayType = typeof array; /// readonly [false, 1, ""]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |