Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing string literals to index signatures

I’ve currently got MyTest which simply maps over an object:

type MyTest<T> = {
  [P in keyof T]: T[P];
};

type Result = MyTest<{hello: 'world', foo: 2}>;
//   ^? type Result = { hello: 'world', foo: 2 }  👍

However If I pass a string literal like hello instead of an object, I get hello back. Question is why?

type Result2 = MyTest<"hello">;
//   ^? type Result2 = "hello"  đź‘€

I’m thinking of 2 scenarios here:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. The iteration does indeed happen with the keys being the property names a string may have such as toString(). In this case I’d expect an object back with ~35 keys all of which would carry the value of never?
  2. The iteration never happens cause there’s nothing to iterate on. What’s the default value then?

>Solution :

This behaviour has been discussed here. Using mapped types to map over primitives will just return the primitve itself.

Mapped types declared as { [ K in keyof T ]: U } where T is a type parameter are known as homomorphic mapped types, which means that the mapped type is a structure preserving function of T. When type parameter T is instantiated with a primitive type the mapped type evaluates to the same primitive.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading