Ts-toolbelt: Why didn't you create a 'Defer' type alias?

Created on 4 Apr 2020  路  2Comments  路  Source: millsp/ts-toolbelt

馃 Question

In other discussions, you mention the use of extends infer X syntax as a way to defer evaluation of a type by the typescript compiler until we've received type parameters.

Discussion here: https://github.com/pirix-gh/ts-toolbelt/issues/102
And here: https://github.com/pirix-gh/ts-toolbelt/issues/5

Describe your question

Is there a reason you've directly used this syntax in all of your types and haven't created a 'Defer' type, such as type Defer<T, TAs = T> = T extends infer X ? Cast<X, TAs> : never;?

Search tags, topics

typescript #deferred #type-evaluation



question

Most helpful comment

Because if you would do that... Let's suppose you have a recursive type A. Then you want a deferred type A. If you did type DeferA<...> = Defer<A<...>>, then the type A<...> would be expanded by TypeScript before it's even passed to Defer<...>, thus making Defer pointless.

TypeScript tries to expand types as it traverses them. ... extends infer X is the only way to prevent it from doing this. In essence, a Defer type won't work because it will expand (compute) the recursive type before it has even been passed to Defer.

All 2 comments

Because if you would do that... Let's suppose you have a recursive type A. Then you want a deferred type A. If you did type DeferA<...> = Defer<A<...>>, then the type A<...> would be expanded by TypeScript before it's even passed to Defer<...>, thus making Defer pointless.

TypeScript tries to expand types as it traverses them. ... extends infer X is the only way to prevent it from doing this. In essence, a Defer type won't work because it will expand (compute) the recursive type before it has even been passed to Defer.

Of course... thanks for the break down!

Was this page helpful?
0 / 5 - 0 ratings