yaquawa
yaquawa

Reputation: 7338

Get type of an object by index number?

I have a usecase like:

type ExtractTypeFromIndex<I> = ???

type foo = { a:string; b:number }
type a = ExtractTypeFromIndex<0> // string
type b = ExtractTypeFromIndex<1> // number

Anyone knows how to implement the ExtractTypeFromIndex?

Upvotes: 0

Views: 161

Answers (1)

slaid3r
slaid3r

Reputation: 176

You don't have an index in object that is not an array.

The same type foo could be defined as type foo = { b: number, a: string } How would the ExtractTypeFromIndex be expected to behave?

If you'd like to access type of the nth element in a array type like

type SomeArray = [string, number];

You can do this like this

type SomeArray = [string, number];

// valid
const a: SomeArray[0] = 'string';
const b: SomeArray[1] = 4

// invalid
const c: SomeArray[1] = 'string';
const d: SomeArray[0] = 4

Link to TS Playground

https://www.typescriptlang.org/play?ssl=1&ssc=1&pln=9&pc=26#code/C4TwDgpgBAyg9gWwgQQE6oIYigXigbQGdhUBLAOwHMAaKcgVwQCMJUBdAbgCguB6XqADcMAG1IATLgGM45YlAwAuWIhTos+AAxtcUAOTEyVPdxlzgUJsvhI0mEPgCMOvABYe-KBWFjJZ+VLWqnYazroGJBSUJtKy8uJBtuoO2rquQA

Upvotes: 2

Related Questions