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)
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.New TS Handbook has a mention about
[number]
syntax: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...
It was very educational. Thx for the post.
Wow!
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...
You're my friend!
A helpful cheat sheet. Thanks!