Let's delve into the realm of mathematical sets theory. As per Wikipedia:
In the field of mathematics, when set A
contains all elements present in set B
, we say that set A
is a subset of set B
. In this scenario, set B
becomes a superset of A
. It's worth noting that if sets A
and B
are not identical, then A
is considered a proper subset of B
. The relationship where one set is within another is referred to as inclusion (or sometimes containment). Furthermore, even the empty set can be classified as a subset of any given set.
This same principle is applied in typescript when dealing with unions, intersections, and assignments.
For instance, the any
type acts as a superset encompassing every conceivable type. Therefore, every primitive, complex, or custom type that exists is essentially a subset of the any
type.
Consider number literals — if we define number
as [-Infinity, +Infinity]
, enveloping all numbers, and create type A = 1
; since every element in A
falls under the number
category, A
is categorized as a subset of number
. This allows for operations like:
let num: number = 1
The same concept applies to string literals. While string
encompasses all possible strings, a literal such as type B = 'str'
signifies only one feasible value.
To summarize, when assigning values to a variable typed with A
, it must align with the subset type of A
.
When handling non-primitive types like objects, the superset denotes a less defined type:
type Superset = {a: string}
type Subset = {a: string; b: string}
In typescript, the representation of an empty set is denoted by never
. Since the empty set serves as a subset of any type, scenarios like the following are perfectly valid:
const a: number = {} as never;
In the context of generics, A extends B
implies that A
is a subset of B
, rather than being equivalent to B
. Consequently, the compiler faces challenges in pinpointing the precise generic argument type, resorting to intersection when type guard assessment is initiated.
For further insights on set theory in typescript, refer to this enlightening blog post