Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the type { [x: string]: any } mean? [duplicate]

Tags:

typescript

I read this article and I cannot understand the signature:

type FuncWithOneObjectArgument<P extends { [x: string]: any }, R> = (props: P) => R;

What does { [x: string]: any} mean? I supposed it's a dictionary with values of any type and keys of... what? List? Of strings?! What does x mean? I tried to remove x but it leads to syntax error... How to read the type?

like image 831
RandomB Avatar asked Oct 28 '25 10:10

RandomB


1 Answers

It define what the keys of your object can be. In your case, your keys can only be of type string. And your values can be whatever.

The reason behind this is that, in typescript, you can define an object to have certain property :

type obj = {property1: string, property2: any};

This create an type of object what MUST have both property to be valid.

Because of that, there is not intuitive way to define key type. Hense why we use the square bracket.

type obj = {[keys: string]: any};

For type like string and int it seams to be pointless, but you could use the union type operator to define what your keys can be :

type obj = {[keys in 'key1'|'key2'|'key3']: any};

This synthax is saying that your keys can only be key1, key2 or key3.

like image 155
Nicolas Avatar answered Oct 30 '25 02:10

Nicolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!