Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why any extends X ? A : B give A | B in typescript?

Tags:

typescript

type TestAny = any extends 'a' ? 1 : 2 // => 1 | 2  why??? how to understand?
type TestUnknown = unknown extends 'a' ? 1 : 2 // => 2
type TestStringA = 'a' extends 'a' ? 1 : 2 // => 1

type SomeUnion = 'a' | 'b'
type UnionDistribute<T> = T extends 'a' ? 1 : 2
type t0 = UnionDistribute<SomeUnion>  // => 1 | 2  // any work like an union

Why any extends 'a' ? 1: 2 give 1 | 2, this work as a union. I tried to google to find some explanation but failed.

palyground

like image 540
huanguolin Avatar asked Aug 12 '21 09:08

huanguolin


People also ask

Why we should not use any in TypeScript?

any. ❌ Don't use any as a type unless you are in the process of migrating a JavaScript project to TypeScript. The compiler effectively treats any as “please turn off type checking for this thing”. It is similar to putting an @ts-ignore comment around every usage of the variable.

Can you extend types in TypeScript?

To extend types in TypeScript, we can use the extends keyword. to create the UserEvent interface that extends the Event type. We extend it by adding the string UserId field in UserEvent and inheriting the rest from Event .

What is ?: In TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

What is @types in TypeScript?

What is a type in TypeScript. In TypeScript, a type is a convenient way to refer to the different properties and functions that a value has. A value is anything that you can assign to a variable e.g., a number, a string, an array, an object, and a function. See the following value: 'Hello'


1 Answers

See microsoft/TypeScript#40049 for an authoritative answer to this question, although it doesn't in my opinion shed much light on the underlying reason.

Specifically this comment:

@jack-williams commented on Aug 14, 2020:

This isn't especially well-documented outside of the source-code, but in the checker you'll find in the relevant place:

// Return union of trueType and falseType for 'any' since it matches anything
if (checkType.flags & TypeFlags.Any) {

So any is treated like a wildcard that matches both branches.

Currently you can find the code on line 15239 (GitHub won't let you link to specific lines in files as big as this one), and it was introduced in this commit inside microsoft/TypeScript#21316, the pull request that implemented conditional types in the first place. So it's been this way as long as conditional types have existed.

That's the closest you'll get to "why" this happens. The official answer is "since it matches anything".

like image 127
jcalz Avatar answered Sep 27 '22 17:09

jcalz