求教一个 TypeScript 获取数组类型?

TypeScript 如何获取一个数组的具体类型

eg:

const arr1 = [1,2,3] -> number

const arr2 = ['1','2','3'] -> string

const arr3 = [{data:1},{data:2},{data:3}] -> {data:number}

我现在有一个写法是通过typeof,但是总感觉哪里不对(~ ̄▽ ̄)~

eg:


type a1 = typeof arr1[0]

type a2 = typeof arr2[0]

type a3 = typeof arr3[0]

希望不吝赐教!

阅读 2.2k
2 个回答
const arr1 = [1,2,3]

const arr2 = ['1','2','3']

const arr3 = [{data:1},{data:2},{data:3}]

type InferArray<T> = T extends (infer S)[] ? S : never;

type d1 = InferArray<typeof arr1> // number
type d2 = InferArray<typeof arr2> // string
type d3 = InferArray<typeof arr3> // {data:number}
type ItemType<L extends any[]> = L extends Array<infer T> ? T : never;

const x = [''];

type X = typeof x;
// string[]

type X2 = ItemType<X>
// string
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题