# TypeScript 内置方法

TypeScript 本质上是 JavaScript 的超集,因此它继承了所有 JavaScript 的内置方法,并且添加了一些类型检查和增强功能。以下是一些 TypeScript 开发中常用的内置方法和功能:

# 1. 类型断言(Type Assertions)

类型断言用于明确告诉编译器变量的类型,可以使用 as 语法或尖括号语法。

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

// 或者
let strLength2: number = (<string>someValue).length;

# 2. 泛型(Generics)

泛型允许你创建可以适用于多种类型的组件。它提供了编写灵活且强类型的代码的能力。

function identity<T>(arg: T): T {
  return arg;
}

let output = identity<string>("Hello");

# 3. 内置类型(Utility Types)

TypeScript 提供了一些常用的内置类型工具,它们允许你根据现有类型生成新类型:

  • Partial:将类型 T 中的所有属性设为可选。
  • Required:将类型 T 中的所有属性设为必选。
  • Readonly:将类型 T 中的所有属性设为只读。
  • Pick<T, K extends keyof T>:从类型 T 中挑选一些属性生成新类型。
  • Omit<T, K extends keyof any>:从类型 T 中移除一些属性生成新类型。
  • Record<K extends keyof any, T>:构造一个对象类型,其属性键为 K,属性值为 T。
  • ReturnType:获取函数类型 T 的返回类型。

# 4. keyof 操作符

keyof 操作符用于获取某种类型的所有键,返回一个联合类型。

type Person = { name: string; age: number };
type PersonKeys = keyof Person; // 'name' | 'age'

# typeof 操作符

let s = "hello";
type Str = typeof s; // string

# 6.条件类型(Conditional Types)

条件类型用于根据条件选择一种类型。

type IsString<T> = T extends string ? true : false;

type A = IsString<string>;  // true
type B = IsString<number>;  // false

# 7.交叉类型(Intersection Types)

交叉类型用于组合多个类型为一个类型,要求满足所有的类

interface A {
  a: string;
}
interface B {
  b: number;
}

type C = A & B;

const obj: C = { a: "hello", b: 42 };

# 8. 联合类型(Union Types)

联合类型允许变量是多种类型之一。

function printId(id: number | string) {
  console.log("Your ID is: " + id);
}

# 9. in 操作符

in 操作符用于类型缩小,通常与条件语句一起使用。

type Fish = { swim: () => void };
type Bird = { fly: () => void };

function move(animal: Fish | Bird) {
  if ("swim" in animal) {
    return animal.swim();
  }

  return animal.fly();
}

# 10. instanceof 操作符

class Dog {
  bark() {
    console.log("Woof!");
  }
}

class Cat {
  meow() {
    console.log("Meow!");
  }
}

function makeNoise(animal: Dog | Cat) {
  if (animal instanceof Dog) {
    animal.bark();
  } else {
    animal.meow();
  }
}