DEV Community

Andreas Bergqvist
Andreas Bergqvist

Posted on

JavaScrpt typeOf TypeScript - get types from data using typeof

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 the data in a object or array. The following ways are great to create your types!

Lets say you have the following data:

const data = {
  value: 123,
  text: 'text'
};

Then you can create a type bases on that using:

type Data = typeof data;
// type Data = {
//   value: number;
//   text: string;
// }

You can do the same with nested objects:

const data = {
  value: 123,
  text: 'text',
  subData: {
    value: false
  }
};
type Data = typeof data;
// type Data = {
//   value: number;
//   text: string;
//   subData: {
//     value: boolean;
//   };
// }

Since TypeScript 3.4 you can do the following if you have an array of strings (notice the as const):

const data = ['text 1', 'text 2'] as const;
type Data = typeof data[number];
// type Data = "text 1" | "text 2"

It's also possible to get types from arrays with objects:

const locales = [
  {
    locale: 'se',
    language: 'Swedish',
  },
  {
    locale: 'en',
    language: 'English',
  }
] as const;
type Locale = typeof locales[number]['locale'];
// type Locale = "se" | "en"

And it's also possible to get types from keys:

const currencySymbols = {
  GBP: '£',
  USD: '$',
  EUR: '',
}
type CurrencySymbol = keyof typeof currencySymbols;
// type CurrencySymbol = "GBP" | "USD" | "EUR"

A notice about as const vs using <const>. They both work the same but the <const> will fail in a .tsx-file (React).

const data = ['text 1', 'text 2'] as const;
// is the same as
const data = <const>['text 1', 'text 2'];

Top comments (8)

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!