Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript Basic Types

TypeScript Basic Types

Basic types allow developers to describe the structure and intent of data more accurately.

The data types included in TypeScript are shown in the following table:

Type Description Example
string Represents text data let name: string = "Alice";
number Represents numbers, including integers and floating-point values let age: number = 30;
boolean Represents boolean values true or false let isDone: boolean = true;
array Represents an array of elements of the same type let list: number[] = [1, 2, 3];
tuple Represents an array with known types and length let person: [string, number] = ["Alice", 30];
enum Defines a set of named constants enum Color { Red, Green, Blue };
any Any type, with no type checking let value: any = 42;
void No return value (commonly used in functions) function log(): void {}
null Represents a null value let empty: null = null;
undefined Represents undefined let undef: undefined = undefined;
never Represents no return value function error(): never { throw new Error("error"); }
object Represents non-primitive types let obj: object = { name: "Alice" };
union Union type, indicating it can be one of multiple types `let id: string
unknown Uncertain type, requires a type check before use let value: unknown = "Hello";

**Note:** TypeScript and JavaScript do not have an integer type.

1. string (String)

Represents text data; it can only store strings and is typically used to describe textual information.



let message: string = "Hello, TypeScript!";

**Template literals:** TypeScript supports template literals, defined with backticks ` (remember, not single quotes '), which allow variables or expressions to be embedded in strings, making them ideal for multiline text and variable concatenation.

let name: string = "Alice";

let greeting: string = `Hello, ${name}! Welcome to TypeScript.`;

console.log(greeting); // 输出:Hello, Alice! Welcome to TypeScript.

2. number (Number)

TypeScript uses number to represent all numbers, including integers and floating-point values.



let age: number = 25;

let temperature: number = 36.5;

3. boolean (Boolean)

Represents the logical values true or false, used for conditional checks.



let isCompleted: boolean = false;

4. array (Array)

Can represent a group of elements of the same type. Two syntaxes can be used: type[] or Array with a type parameter.



let numbers: number[] = [1, 2, 3];

let names: Array = ["Alice", "Bob"];

5. tuple (Tuple)

Represents an array with a known number and types of elements. Each element can be of a different type, making it suitable for representing data with a fixed structure.



let person: [string, number] = ["Alice", 25];

6. enum (Enum)

Used to define a set of named constants. By default, enum values start at 0 and increment.

enum Color {

  Red,

  Green,

  Blue,

}

let favoriteColor: Color = Color.Green;

7. any type

can represent any type. Suitable for situations where the data type is uncertain, but it should be used with caution because any bypasses type checking.

let randomValue: any = 42;

randomValue = "hello";

An any value is a data type used by TypeScript for variables whose type is unclear during programming; it is commonly used in the following three situations.

1. When a variable's value changes dynamically, such as input from a user, the any type allows these variables to skip type checking at compile time. Example code is as follows:



let x: any = 1;    // 数字类型

x = 'I am who I am';    // 字符串类型

x = false;    // 布尔类型

When rewriting existing code, any allows type checking to be optionally included or removed at compile time. Example code is as follows:

let x: any = 4;

x.ifItExists();    // 正确,ifItExists方法在运行时可能存在,但这里并不会检查

x.toFixed();    // 正确

When defining an array that stores data of various types, example code is as follows:

let arrayList: any[] = [1, false, 'fine'];

arrayList[1] = 100;

8. void (empty type)

Used for functions that do not return a value. When declaring a variable, the void type means it can only be assigned null or undefined.



function logMessage(message: string): void {

  console.log(message);

}

9. null and undefined

null and undefined represent 'null value' and 'undefined' respectively. By default, they are subtypes of all types, but strict checking can be enabled via strictNullChecks.

let empty: null = null;

let notAssigned: undefined = undefined;

null

In JavaScript, null means "nothing".

null is a special type with only one value. It represents an empty object reference.

Using typeof to check null returns object.

undefined

In JavaScript, undefined is a variable that has not been assigned a value.

Using typeof on a variable without a value returns undefined.

Null and Undefined are subtypes of any other type (including void) and can be assigned to other types such as the number type; in that case, the assigned type becomes null or undefined. However, in TypeScript, enabling strict null checks (--strictNullChecks) makes it so that null and undefined can only be assigned to void or their corresponding types. Example code is as follows:

// 启用 --strictNullChecks

let x: number;

x = 1; // 编译正确

x = undefined;    // 编译错误

x = null;    // 编译错误

In the example above, variable x can only be of the number type. If a type might be null or undefined, you can use | to support multiple types. Example code is as follows:

// 启用 --strictNullChecks

let x: number | null | undefined;

x = 1; // 编译正确

x = undefined;    // 编译正确

x = null;    // 编译正确

For more information, see:JavaScript typeof, null, and undefined

10. never type

Represents no return value; typically used for functions that throw errors or enter infinite loops, indicating the function will never terminate normally.

function throwError(message: string): never {

  throw new Error(message);

}

never is a subtype of all other types (including null and undefined), representing values that never occur. This means a variable declared as type never can only be assigned a never value; in functions it typically manifests as throwing an exception or being unable to reach a termination point (such as an infinite loop). Example code is as follows:

let x: never;

let y: number;



// Compilation error, numeric type cannot be converted to never type

x = 123;



// Runs correctly, never type can be assigned to never type

x = (()=>{ throw new Error('exception')})();



// Runs correctly, never type can be assigned to number type

y = (()=>{ throw new Error('exception')})();



// Functions that return never can be cases that throw an exception

function error(message: string): never {

    throw new Error(message);

}



// Functions whose return value is never can be termination points that cannot be executed

function loop(): never {

    while (true) {}

}

11. object (Object type)

Represents non-primitive values, suitable for complex object structures.



let person: object = { name: "Alice", age: 30 };

12. Union types (Union)

Indicates that a variable can be one of multiple types. Implemented with the | symbol.



let id: string | number;

id = "123";

id = 456;

13. unknown (uncertain type)

Similar to any but stricter. It must pass a type check before being assigned to a variable of another type.



let value: unknown = "Hello";

if (typeof value === "string") {

  let message: string = value;

}

14. Type Assertions

Type assertions let developers explicitly tell the compiler the type of a variable, commonly used when it cannot be inferred. You can use the as syntax or angle-bracket syntax.



let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;

15. Literal types

Literal types restrict a variable to specific values, and can be combined with union types to define specific states of a variable.



let direction: "up" | "down" | "left" | "right";

direction = "up";

Through these types, TypeScript provides stronger type safety and code-checking capabilities, enabling developers to express data and intent more clearly and accurately and reducing runtime errors.


Example

The following example demonstrates the definition and use of the main basic types in TypeScript, simulating a user object and related operation functions:

Example

// Define an enum type to represent user roles

enum

Role

{

  Admin

,

  User

,

  Guest

,

}

// Use an interface to define the structure of a user

interface

User

{

  id

:

number

;

             

// number type, used to uniquely identify a user

  username

:

string

;

       

// string type, representing the username

  isActive

:

boolean

;

       

// boolean type, indicating whether a user is active

  role

:

Role

;

             

// enum type, used to represent user roles

  hobbies

:

string

[

]

;

       

// array type, storing a user's hobbies

  contactInfo

:

[

string

,

number

]

;

// tuple type, a tuple containing a phone number in the format: [area code, phone number]

}

// Create a user object conforming to the structure of the User interface

const

user

:

User

=

{

  id

:

1

,

  username

:

"Alice"

,

  isActive

:

true

,

  role

:

Role.

User

,

  hobbies

:

[

"Reading"

,

"Gaming"

]

,

  contactInfo

:

[

"+1"

,

123456789

]

,

}

;

// Define a function returning a string to get user information

function

getUserInfo

(

user

:

User

)

:

string

{

 

return

`User $

{

user.

username

}

is $

{

user.

isActive

?

"active"

:

"inactive"

}

with role $

{

Role

[

user.

role

]

}

`

;

}

// Use the void type to define a function that prints user information

function

printUserInfo

(

user

:

User

)

:

void

{

  console.

log

(

getUserInfo

(

user

)

)

;

}

// Define a union-type function parameter that accepts a user ID (number) or username (string)

function

findUser

(

query

:

number

|

string

)

:

User

|

undefined

{

 

// Use typeof to determine the type of query

 

if

(

typeof

query

===

"number"

)

{

   

// If it is a number, look up the user by ID

   

return

query

===

user.

id

?

user

:

undefined

;

 

}

else

if

(

typeof

query

===

"string"

)

{

   

// If it is a string, look up the user by username

   

return

query

===

user.

username

?

user

:

undefined

;

 

}

 

return

undefined

;

}

// Define a never-type function to handle abnormal program conditions

function

throwError

(

message

:

string

)

:

never

{

 

throw

new

Error

(

message

)

;

}

// Use the any type to handle data of unknown type

let unknownData

:

any

=

"This is a string"

;

unknownData

=

42

;

// Reassign to a number; the type is any

// Use the unknown type to handle uncertain data, which is safer

let someData

:

unknown

=

"Possible data"

;

if

(

typeof

someData

===

"string"

)

{

  console.

log

(

`Length of data

:

$

{

(

someData as string

)

.

length

}

`

)

;

}

// Call each function and test

printUserInfo

(

user

)

;

                   

// Print user information

console.

log

(

findUser

(

1

)

)

;

             

// Look up a user by ID

console.

log

(

findUser

(

"Alice"

)

)

;

       

// Look up a user by username

// Use variables of type null and undefined

let emptyValue

:

null

=

null

;

let uninitializedValue

:

undefined

=

undefined

;

** Note:**