基础类型 in TypeScript
primitive 类型 in TypeScript: 字符串, 数字, 布尔值, 数组, tuple, enum, and 更多.
你将学到
- primitive 类型: 字符串, 数字, and 布尔值
- 如何 类型数组 and tuples
- 什么特殊类型任何, unknown, and 空做
- 当到 use 从不 and 对象类型
概念讲解
Primitive Types
TypeScript has three main primitive types that mirror JavaScript's primitives: 字符串 for text, 数字 for all numeric values (integers and floats are both 数字), and 布尔值 for 真/假. You annotate a variable with a colon followed by the type name: let 数量: 数字 = 10. These are the building blocks of every TypeScript program.
Arrays and Tuples
An array type is written as 类型[] or 数组<类型> — for example, 数字[] is an array of numbers. A tuple is a fixed-length array where each position has a specific type: [字符串, 数字] describes a pair where the first element is a string and the second is a number. Tuples are useful for things like [statusCode, 消息] pairs or CSV row data.
Special Types
Beyond the primitives, TypeScript has several special types. 任何 disables type checking entirely — avoid it. unknown is a type-safe alternative to 任何: it accepts any value but forces you to check the type before using it. 空 means a function returns nothing. 从不 represents a value that never occurs (like a function that always throws). 对象 is the type for any non-primitive value.
示例代码
// Primitives
let name: string = "Alice";
let score: number = 95.5;
let passed: boolean = true;
// Arrays
let scores: number[] = [90, 85, 92];
let names: Array<string> = ["Alice", "Bob"];
// Tuple — fixed length, typed positions
let response: [number, string] = [200, "OK"];
// Special types
let data: unknown = JSON.parse('{"x":1}');
if (typeof data === "object" && data !== null) {
console.log("Got an object");
}
function logMessage(msg: string): void {
console.log(msg);
}
Primitives cover 大多数变量. 数组 use 类型[] 语法. Tuples fix 长度 and 每-位置类型. unknown 是 safe alternative 到任何.
动手试一试
- JSON 到 TypeScript
Generate 输入接口从 JSON 到 see 基础类型 in use.
- JSON Formatter
格式 JSON 数据 and 理解 shapes TypeScript 描述.
常见错误
错误写法
Using 任何到 silence 类型错误
正确做法
Use unknown 相反. 它 forces 你到 验证类型之前 use, keeping 类型 safety 虽然接受 arbitrary 数据.
错误写法
Confusing 数字使用 separate int and float 类型
正确做法
TypeScript 有仅 one 数字类型. 两者都 42 and 3.14 是数字. 那里是 否 int or float distinction.
练习 基础类型 in TypeScript
5 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。