iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🗂

What Are "Types" in TypeScript?

に公開

What is a "Type" in TypeScript in the First Place?

In the previous article, I mentioned tagged unions, but what exactly is a "type" in TypeScript?
Let's dive a little deeper into this.

No Impact at Runtime

As mentioned in the previous article, TypeScript is transpiled into JavaScript before execution. Therefore, the types described in TypeScript code, like the ones below, do not affect the code at runtime.

interface Operator {
    kind: 'operator';
    name: string;
}

interface Engineer {
    kind: 'engineer';
    name: string;
    programmingLanguage: string;
}

type Employee = Operator | Engineer;

You can simply think of types as something used for type checking during compilation.

Structural Typing System is Available

In static typed languages like Java, a compilation error may occur if there is a mismatch between the number of properties specified in the type and the number of properties specified during assignment (though this can be avoided by specifying them in a constructor, etc.).
However, TypeScript uses a system called structural typing, where an error does not occur even if the number of properties does not match.
For example:

interface Employee {
    name: string;
    birthday: string;
    section: string;
}

const taro = {
    name: 'taro';
    birthday: '2000/01/01';
    section: 'sales';
    hobby: 'listening to music';
}

const e: Employee = taro;

The code above does not result in an error.

Think in Terms of Subsets

Why doesn't the description above result in an error?
This is because types in TypeScript can be thought of as subsets.
If a value is included as a subset, it will not cause an error during type checking.
In the example above, it can be represented by the following Venn diagram:

Venn Diagram

So, What Exactly is a "Type" in TypeScript?

A type in TypeScript can be thought of as a set of values (a domain).
The never type is an empty set, a literal type is a set containing a single value, and a union of literal types is a union of sets, and so on.
By thinking of them as sets, it becomes easier to understand concepts like structural typing and excess property checking in TypeScript.

Reference: Effective TypeScript

Discussion