Skip to content

TypeScript 语言基础

TypeScript 是 JavaScript 的超集,通过添加静态类型定义,让代码更健壮、更易于维护。

核心知识点

1. 基础类型

  • Primitives (string, number, boolean)
  • Arrays & Tuples
  • Enums
  • Any, Unknown, Void, Never

2. 接口与类型别名

3. 类型断言与类型保护

类型断言 (Type Assertion)

当你知道一个实体的类型比当前类型更具体时。

typescript
let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;

类型保护 (Type Guard)

一些表达式,它们在运行时检查以确保在某个作用域里的类型。

typescript
function isString(x: any): x is string {
  return typeof x === "string";
}

function print(x: unknown) {
  if (isString(x)) {
    console.log(x.toUpperCase()); // OK
  }
}

4. 实战示例

keyof 与 typeof 结合

typescript
const user = {
  id: 1,
  name: 'yu',
}

type User = typeof user;
type UserKeys = keyof User;

// 实现类型安全的属性访问
function getValue(obj: User, key: UserKeys) {
  return obj[key];
}

getValue(user, 'name'); // OK
// getValue(user, 'age'); // Error

函数定义

typescript
function test(): void {}

MIT Licensed | Keep Learning.