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:
- 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 ofnever? - 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.