原文:https://www.typescriptlang.org/docs/handbook/2/everyday-types.html

In this chapter, we’ll cover some of the most common types of values you’ll find in JavaScript code, and explain the corresponding ways to describe those types in TypeScript. This isn’t an exhaustive list, and future chapters will describe more ways to name and use other types.

Types can also appear in many more places than just type annotations. As we learn about the types themselves, we’ll also learn about the places where we can refer to these types to form new constructs.
We’ll start by reviewing the most basic and common types you might encounter when writing JavaScript or TypeScript code. These will later form the core building blocks of more complex types.

The primitives: string, number, and boolean

JavaScript has three very commonly used primitives: string, number, and boolean. Each has a corresponding type in TypeScript. As you might expect, these are the same names you’d see if you used the JavaScript typeofoperator on a value of those types:

  • string represents string values like "Hello, world"
  • number is for numbers like 42. JavaScript does not have a special runtime value for integers, so there’s no equivalent to int or float - everything is simply number
  • boolean is for the two values true and false

The type names String, Number, and Boolean (starting with capital letters) are legal, but refer to some special built-in types that will very rarely appear in your code. Always use string, number, or boolean for types.

Arrays

To specify the type of an array like [1, 2, 3], you can use the syntax number[]; this syntax works for any type (e.g. string[] is an array of strings, and so on). You may also see this written as Array<number>, which means the same thing. We’ll learn more about the syntax T<U> when we cover generics.

Note that [number] is a different thing; refer to the section on tuple types.

any

TypeScript also has a special type, any, that you can use whenever you don’t want a particular value to cause typechecking errors.

When a value is of type any, you can access any properties of it (which will in turn be of type any), call it like a function, assign it to (or from) a value of any type, or pretty much anything else that’s syntactically legal:

  1. let obj: any = { x: 0 };
  2. // None of these lines of code are errors
  3. obj.foo();
  4. obj();
  5. obj.bar = 100;
  6. obj = "hello";
  7. const n: number = obj;

The any type is useful when you don’t want to write out a long type just to convince TypeScript that a particular line of code is okay.

noImplicitAny

When you don’t specify a type, and Typescript can’t infer it from context, the compiler will typically default to any.

You usually want to avoid this, though, because any isn’t type-checked. Use the compiler flag noImplicitAny to flag any implicit any as an error.

Type Annotations on Variables

When you declare a variable using const, var, or let, you can optionally add a type annotation to explicitly specify the type of the variable:

  1. let myName: string = "Alice";

TypeScript doesn’t use “types on the left”-style declarations like int x = 0; Type annotations will always go after the thing being typed.

In most cases, though, this isn’t needed. Wherever possible, TypeScript tries to automatically infer the types in your code. For example, the type of a variable is inferred based on the type of its initializer:

  1. // No type annotation needed -- 'myName' inferred as type 'string'
  2. let myName = "Alice";

For the most part you don’t need to explicitly learn the rules of inference. If you’re starting out, try using fewer type annotations than you think - you might be surprised how few you need for TypeScript to fully understand what’s going on.

Functions

Functions are the primary means of passing data around in JavaScript. TypeScript allows you to specify the types of both the input and output values of functions.

Parameter Type Annotations

When you declare a function, you can add type annotations after each parameter to declare what types of parameters the function accepts. Parameter type annotations go after the parameter name:

  1. // Parameter type annotation
  2. function greet(name: string) {
  3. console.log("Hello, " + name.toUpperCase() + "!!");
  4. }

When a parameter has a type annotations, arguments to that function will be checked:

  1. // Would be a runtime error if executed!
  2. greet(42);

Argument of type 'number' is not assignable to parameter of type 'string'.

Even if you don’t have type annotations on your parameters, TypeScript will still check that you passed the right number of arguments.

Return Type Annotations

You can also add return type annotations. Return type annotations appear after the parameter list:

  1. function getFavoriteNumber(): number {
  2. return 26;
  3. }

Much like variable type annotations, you usually don’t need a return type annotation because TypeScript will infer the function’s return type based on its return statements. The type annotation in the above example doesn’t change anything. Some codebases will explicitly specify a return type for documentation purposes, to prevent accidental changes, or just for personal preference.

Anonymous Functions

Anonymous functions are a little bit different from function declarations. When a function appears in a place where TypeScript can determine how it’s going to be called, the parameters of that function are automatically given types.

Here’s an example:

  1. // No type annotations here, but TypeScript can spot the bug
  2. const names = ["Alice", "Bob", "Eve"];
  3. // Contextual typing for function
  4. names.forEach(function (s) {
  5. console.log(s.toUppercase());
  6. });
  1. Property 'toUppercase' does not exist on type 'string'. Did you mean 'toUpperCase'?
  1. // Contextual typing also applies to arrow functions
  2. names.forEach((s) => {
  3. console.log(s.toUppercase());
  4. });
  1. Property 'toUppercase' does not exist on type 'string'. Did you mean 'toUpperCase'?

Even though the parameter s didn’t have a type annotation, TypeScript used the types of the forEach function, along with the inferred type of the array, to determine the type s will have.

This process is called contextual typing because the context that the function occurred in informed what type it should have. Similar to the inference rules, you don’t need to explicitly learn how this happens, but understanding that it does happen can help you notice when type annotations aren’t needed. Later, we’ll see more examples of how the context that a value occurs in can affect its type.

Object Types

Apart from primitives, the most common sort of type you’ll encounter is an object type. This refers to any JavaScript value with properties, which is almost all of them! To define an object type, we simply list its properties and their types.

For example, here’s a function that takes a point-like object:

  1. // The parameter's type annotation is an object type
  2. function printCoord(pt: { x: number; y: number }) {
  3. console.log("The coordinate's x value is " + pt.x);
  4. console.log("The coordinate's y value is " + pt.y);
  5. }
  6. printCoord({ x: 3, y: 7 });

Here, we annotated the parameter with a type with two properties - x and y - which are both of type number. You can use , or ; to separate the properties, and the last separator is optional either way.
The type part of each property is also optional. If you don’t specify a type, it will be assumed to be any.

Optional Properties

Object types can also specify that some or all of their properties are optional. To do this, add a ? after the property name:

  1. function printName(obj: { first: string; last?: string }) {
  2. // ...
  3. }
  4. // Both OK
  5. printName({ first: "Bob" });
  6. printName({ first: "Alice", last: "Alisson" });

In JavaScript, if you access a property that doesn’t exist, you’ll get the value undefined rather than a runtime error. Because of this, when you read from an optional property, you’ll have to check for undefined before using it.

  1. function printName(obj: { first: string; last?: string }) {
  2. // Error - might crash if 'obj.last' wasn't provided!
  3. console.log(obj.last.toUpperCase());

Object is possibly 'undefined'.

  1. if (obj.last !== undefined) {
  2. // OK
  3. console.log(obj.last.toUpperCase());
  4. }
  5. // A safe alternative using modern JavaScript syntax:
  6. console.log(obj.last?.toUpperCase());
  7. }

Union Types

TypeScript’s type system allows you to build new types out of existing ones using a large variety of operators. Now that we know how to write a few types, it’s time to start combining them in interesting ways.

Defining a Union Type

The first way to combine types you might see is a union type. A union type is type formed from two or more other types, representing values that may be any one of those types. We refer to each of these types as the union’s members.
Let’s write a function that can operate on strings or numbers:

  1. function printId(id: number | string) {
  2. console.log("Your ID is: " + id);
  3. }
  4. // OK
  5. printId(101);
  6. // OK
  7. printId("202");
  8. // Error
  9. printId({ myID: 22342 });
  1. Argument of type '{ myID: number; }' is not assignable to parameter of type 'string | number'.
  2. Type '{ myID: number; }' is not assignable to type 'number'.

Working with Union Types

It’s easy to provide a value matching a union type - simply provide a type matching any of the union’s members. If you have a value of a union type, how do you work with it?

TypeScript will only allow you to do things with the union if that thing is valid for every member of the union. For example, if you have the union string | number, you can’t use methods that are only available on string:

  1. function printId(id: number | string) {
  2. console.log(id.toUpperCase());
  3. }
  1. Property 'toUpperCase' does not exist on type 'string | number'.
  2. Property 'toUpperCase' does not exist on type 'number'.<br />


The solution is to narrow the union with code, the same as you would in JavaScript without type annotations.Narrowing occurs when TypeScript can deduce a more specific type for a value based on the structure of the code.For example, TypeScript knows that only a string value will have a typeof value "string":

  1. function printId(id: number | string) {
  2. if (typeof id === "string") {
  3. // In this branch, id is of type 'string'
  4. console.log(id.toUpperCase());
  5. } else {
  6. // Here, id is of type 'number'
  7. console.log(id);
  8. }
  9. }

Another example is to use a function like Array.isArray:

  1. function welcomePeople(x: string[] | string) {
  2. if (Array.isArray(x)) {
  3. // Here: 'x' is 'string[]'
  4. console.log("Hello, " + x.join(" and "));
  5. } else {
  6. // Here: 'x' is 'string'
  7. console.log("Welcome lone traveler " + x);
  8. }
  9. }

Notice that in the else branch, we don’t need to do anything special - if x wasn’t a string[], then it must have been a string.

Sometimes you’ll have a union where all the members have something in common. For example, both arrays and strings have a slice method. If every member in a union has a property in common, you can use that property without narrowing:

  1. // Return type is inferred as number[] | string
  2. function getFirstThree(x: number[] | string) {
  3. return x.slice(0, 3);
  4. }

It might be confusing that a union of types appears to have the intersection of those types’ properties. This is not an accident - the name union comes from type theory. The union number | string is composed by taking the union of the values from each type. Notice that given two sets with corresponding facts about each set, only the intersection of those facts applies to the union of the sets themselves. For example, if we had a room of tall people wearing hats, and another room of Spanish speakers wearings hats, after combining those rooms, the only thing we know about every person is that they must be wearing a hat.

Type Aliases
We’ve been using object types and union types by writing them directly in type annotations. This is convenient, but it’s common to want to use the same type more than once and refer to it by a single name.

A type alias is exactly that - a name for any type. The syntax for a type alias is:

  1. type Point = {
  2. x: number;
  3. y: number;
  4. };
  5. // Exactly the same as the earlier example
  6. function printCoord(pt: Point) {
  7. console.log("The coordinate's x value is " + pt.x);
  8. console.log("The coordinate's y value is " + pt.y);
  9. }
  10. printCoord({ x: 100, y: 100 });

You can actually use a type alias to give a name to any type at all, not just an object type. For example, a type alias can name a union type:

  1. type ID = number | string;

Note that aliases are only aliases - you cannot use type aliases to create different/distinct “versions” of the same type. When you use the alias, it’s exactly as if you had written the aliased type. In other words, this code might look illegal, but is OK according to TypeScript because both types are aliases for the same type:

  1. type UserInputSanitizedString = string;
  2. function sanitizeInput(str: string): UserInputSanitizedString {
  3. return sanitize(str);
  4. }
  5. // Create a sanitized input
  6. let userInput = sanitizeInput(getInput());
  7. // Can still be re-assigned with a string though
  8. userInput = "new input";

Interfaces

An interface declaration is another way to name an object type:

  1. interface Point {
  2. x: number;
  3. y: number;
  4. }
  5. function printCoord(pt: Point) {
  6. console.log("The coordinate's x value is " + pt.x);
  7. console.log("The coordinate's y value is " + pt.y);
  8. }
  9. printCoord({ x: 100, y: 100 });

Just like when we used a type alias above, the example works just as if we had used an anonymous object type. TypeScript is only concerned with the structure of the value we passed to printCoord - it only cares that it has the expected properties. Being concerned only with the structure and capabilities of types is why we call TypeScript a structurally typed type system.

Differences Between Type Aliases and Interfaces

Type aliases and interfaces are very similar, and in many cases you can choose between them freely. Almost all features of an interface are available in type, the key distinction is that a type cannot be re-opened to add new properties vs an interface which is always extendable.

Interface Type
Extending an interface`interface Animal {

name: string }interface Bear extends Animal { honey: boolean }const bear = getBear() bear.name bear.honey
| Extending a type via intersectionstype Animal = { name: string }type Bear = Animal & { honey: Boolean }const bear = getBear(); bear.name; bear.honey;
| | Adding new fields to an existing interfaceinterface Window { title: string }interface Window { ts: TypeScriptAPI }const src = ‘const a = “Hello World”‘; window.ts.transpileModule(src, {});
| A type cannot be changed after being createdtype Window = { title: string }type Window = { ts: TypeScriptAPI } // Error: Duplicate identifier ‘Window’.` |

You’ll learn more about these concepts in later chapters, so don’t worry if you don’t understand all of these right away.

For the most part, you can choose based on personal preference, and TypeScript will tell you if it needs something to be the other kind of declaration. If you would like a heuristic, use interface until you need to use features from type.

Type Assertions

Sometimes you will have information about the type of a value that TypeScript can’t know about.

For example, if you’re using document.getElementById, TypeScript only knows that this will return some kind of HTMLElement, but you might know that your page will always have an HTMLCanvasElement with a given ID.

In this situation, you can use a type assertion to specify a more specific type:

  1. const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;

Like a type annotation, type assertions are removed by the compiler and won’t affect the runtime behavior of your code.

You can also use the angle-bracket syntax (except if the code is in a .tsx file), which is equivalent:

  1. const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas");

Reminder: Because type assertions are removed at compile-time, there is no runtime checking associated with a type assertion. There won’t be an exception or null generated if the type assertion is wrong.

TypeScript only allows type assertions which convert to a more specific or less specific version of a type. This rule prevents “impossible” coercions like:

  1. const x = "hello" as number;
  1. Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression
  1. to 'unknown' first.<br />


Sometimes this rule can be too conservative and will disallow more complex coercions that might be valid. If this happens, you can use two assertions, first to ``` any

  1. (or

unknown

  1. , which well introduce later), then to the desired type:```typescript
  2. const a = (expr as any) as T;

Literal Types

In addition to the general types string and number, we can refer to specific strings and numbers in type positions.

One way to think about this is to consider how JavaScript comes with different ways to declare a variable. Both varand let allow for changing what is held inside the variable, and const does not. This is reflected in how TypeScript creates types for literals.

  1. let changingString = "Hello World";
  2. changingString = "Ola Mundo";
  3. // Because `changingString` can represent any possible string, that
  4. // is how TypeScript describes it in the type system
  5. changingString;
  6. // ^ = let changingString: string
  7. const constantString = "Hello World";
  8. // Because `constantString` can only represent 1 possible string, it
  9. // has a literal type representation
  10. constantString;
  11. // ^ = const constantString: "Hello World"

By themselves, literal types aren’t very valuable:

  1. let x: "hello" = "hello";
  2. // OK
  3. x = "hello";
  4. // ...
  5. x = "howdy";
  1. Type '"howdy"' is not assignable to type '"hello"'.

It’s not much use to have a variable that can only have one value!

But by combining literals into unions, you can express a much more useful concept - for example, functions that only accept a certain set of known values:

  1. function printText(s: string, alignment: "left" | "right" | "center") {
  2. // ...
  3. }
  4. printText("Hello, world", "left");
  5. printText("G'day, mate", "centre");
  1. Argument of type '"centre"' is not assignable to parameter of type '"left" | "right" | "center"'.
  1. <br />

Numeric literal types work the same way:

  1. function compare(a: string, b: string): -1 | 0 | 1 {
  2. return a === b ? 0 : a > b ? 1 : -1;
  3. }

Of course, you can combine these with non-literal types:

  1. interface Options {
  2. width: number;
  3. }
  4. function configure(x: Options | "auto") {
  5. // ...
  6. }
  7. configure({ width: 100 });
  8. configure("auto");
  9. configure("automatic");
  1. Argument of type '"automatic"' is not assignable to parameter of type 'Options | "auto"'.
  1. <br />

There’s one more kind of literal type: boolean literals. There are only two boolean literal types, and as you might guess, they are the types true and false. The type boolean itself is actually just an alias for the union true | false.

Literal Inference

When you initialize a variable with an object, TypeScript assumes that the properties of that object might change values later. For example, if you wrote code like this:

  1. const obj = { counter: 0 };
  2. if (someCondition) {
  3. obj.counter = 1;
  4. }

TypeScript doesn’t assume the assignment of 1 to a field which previously had 0 is an error. Another way of saying this is that obj.counter must have the type number, not 0, because types are used to determine both reading_and _writing behavior.

The same applies to strings:

  1. const req = { url: "https://example.com", method: "GET" };
  2. handleRequest(req.url, req.method);
  1. Argument of type 'string' is not assignable to parameter of type '"GET" | "POST"'.
  1. <br />

In the above example req.method is inferred to be string, not "GET". Because code can be evaluated between the creation of req and the call of handleRequest which could assign a new string like "GUESS" to req.method, TypeScript considers this code to have an error.

There are two ways to work around this.
1. You can change the inference by adding a type assertion in either location:

  1. // Change 1:
  2. const req = { url: "https://example.com", method: "GET" as "GET" };
  3. // Change 2
  4. handleRequest(req.url, req.method as "GET");

Change 1 means “I intend for req.method to always have the literal type "GET"”, preventing the possible assignment of "GUESS" to that field after. Change 2 means “I know for other reasons that req.method has the value "GET"“.

  1. You can use as const to convert the entire object to be type literals:
    1. const req = { url: "https://example.com", method: "GET" } as const;
    2. handleRequest(req.url, req.method);
    The as const prefix acts like const but for the type system, ensuring that all properties are assigned the literal type instead of a more general version like string or number.

null and undefined

JavaScript has two primitive values used to signal absent or uninitialized value: null and undefined.
TypeScript has two corresponding types by the same names. How these types behave depends on whether you have the strictNullChecks option on.

strictNullChecks off

With strictNullChecks off, values that might be null or undefined can still be accessed normally, and the values null and undefined can be assigned to a property of any type. This is similar to how languages without null checks (e.g. C#, Java) behave. The lack of checking for these values tends to be a major source of bugs; we always recommend people turn strictNullChecks on if it’s practical to do so in their codebase.

strictNullChecks on

With strictNullChecks on, when a value is null or undefined, you will need to test for those values before using methods or properties on that value. Just like checking for undefined before using an optional property, we can use narrowing to check for values that might be null:

  1. function doSomething(x: string | undefined) {
  2. if (x === undefined) {
  3. // do nothing
  4. } else {
  5. console.log("Hello, " + x.toUpperCase());
  6. }
  7. }

Non-null Assertion Operator (Postfix !)

TypeScript also has a special syntax for removing null and undefined from a type without doing any explicit checking. Writing ! after any expression is effectively a type assertion that the value isn’t null or undefined:

  1. function liveDangerously(x?: number | undefined) {
  2. // No error
  3. console.log(x!.toFixed());
  4. }

Just like other type assertions, this doesn’t change the runtime behavior of your code, so it’s important to only use !when you know that the value can’t be null or undefined.

Enums

Enums are a feature added to JavaScript by TypeScript which allows for describing a value which could be one of a set of possible named constants. Unlike most TypeScript features, this is not a type-level addition to JavaScript but something added to the language and runtime. Because of this, it’s a feature which you should know exists, but maybe hold off on using unless you are sure. You can read more about enums in the Enum reference page.

Less Common Primitives

It’s worth mentioning the rest of the primitives in JavaScript which are represented in the type system. Though we will not go into depth here.

bigint

From ES2020 onwards, there is a primitive in JavaScript used for very large integers, BigInt:

  1. // Creating a bigint via the BigInt function
  2. const oneHundred: bigint = BigInt(100);
  3. // Creating a BigInt via the literal syntax
  4. const anotherHundred: bigint = 100n;

symbol

There is a primitive in JavaScript used to create a globally unique reference via the function Symbol():

  1. const firstName = Symbol("name");
  2. const secondName = Symbol("name");
  3. if (firstName === secondName) {
  4. // Can't ever happen
  5. }

This condition will always return 'false' since the types 'typeof firstName' and 'typeof secondName' have no overlap.