DEV Community

TypeScript - get types from data using typeof

Andreas Bergqvist on April 10, 2019

A great way to make sure the values you set to your variables matches what you would expect is to set specific types to them. If you already have ...
Collapse
 
andyviv profile image
Andy Perlitch

Thanks for the post. Is there documentation on that typeof myConst[number] syntax? Specifically the [number] part is something i've never seen in typescript, and can't find on the doc site.

Collapse
 
karataev profile image
Eugene Karataev • Edited

New TS Handbook has a mention about [number] syntax:

const MyArray = [
    { name: "Alice", age: 15 },
    { name: "Bob", age: 23 },
    { name: "Eve", age: 38 }
];
type T = (typeof MyArray)[number];
Enter fullscreen mode Exit fullscreen mode
Collapse
 
andreasbergqvist profile image
Andreas Bergqvist

Hi, I'm not sure. Been a while since I wrote this and its a gathering of things I read and things I just tested with code...

Collapse
 
solomko2 profile image
sol

It was very educational. Thx for the post.

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

Wow!

Collapse
 
rinatsafin profile image
Rinat Safin • Edited

Very big thanks!
Can you add how to create a type by type/interface (like object) values in typescript?
drive.google.com/file/d/1B-Jv-1VOK...

Collapse
 
jdnichollsc profile image
J.D Nicholls

You're my friend!

Collapse
 
rivayudha profile image
Riva Yudha

A helpful cheat sheet. Thanks!