Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The display of types #19

Open
utterances-bot opened this issue Apr 16, 2022 · 4 comments
Open

The display of types #19

utterances-bot opened this issue Apr 16, 2022 · 4 comments

Comments

@utterances-bot
Copy link

The display of types

Effective TypeScript: The display of types

https://effectivetypescript.com/2022/02/25/gentips-4-display/

Copy link

jfet97 commented Apr 16, 2022

type Resolve<T> = T extends Function ? T : {[K in keyof T]: T[K]} seems to be able to preserve types like number or "42":

type n = Resolve<number> // number
type s42 = Resolve<"42"> // "42"

How is that even possible? Ahah I mean {[K in keyof "42"]: "42"[K]} is definitely not the same as "42".

Copy link
Owner

danvk commented Apr 17, 2022

It is surprising, isn't it? One clue is that keyof gives the methods defined on the wrapper types for primitives:

type K = keyof number;
//   ^? type K = "toString" | "toFixed" | "toExponential" | ...

But still, I think this must be special-cased in the TypeScript compiler. Especially in the case of a literal type, the result is much more specific than you'd expect. Resolve is magical indeed!

Copy link

jfet97 commented Apr 21, 2022

I think I found something: microsoft/TypeScript#12447
{[K in keyof T]: T[K]}is what we now call a homomorphic (previously isomorphic) mapped type, and ahejlsberg said that "when a primitive type is substituted for T in an isomorphic mapped type, we simply produce that primitive type".

Copy link
Owner

danvk commented Apr 23, 2022

So there is a rationale behind this. Nice find @jfet97! It's news to me that "distributing over unions" is a concept that predates conditional types. This behavior was never mentioned in the release notes at the time (2.1 and 2.2).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants