5 个有用的 TypeScript 技巧

2025-06-04

5 个有用的 TypeScript 技巧

1. 创建类型检查函数

interface IDog{
   name:  string;
   age: number;
   kidFriendly: boolean;
}

interface ICat{
   name: string;
   age: number;
   activityLevel: number;
}

type Animal = IDog | ICat;

/** Is the animal a dog ? */
const isDog = (animal: Animal) : animal is IDog => (animal as IDog).kidFriendly !== undefined;

if(isDog(animal)){
   console.log(animal.kidFriendly);
}
Enter fullscreen mode Exit fullscreen mode

更多信息请见:

2. 将接口的所有属性设置为可选

interface IDog{
   name: string;
   age: number;
   kidFriendly: boolean;
}

const dog : Partial<IDog> = {
   name: "Rex"
}
Enter fullscreen mode Exit fullscreen mode

3. 获取函数参数的类型

const walkDog = (dogName: string, distance: number) => { /** ... */ }

const params: Parameters<typeof walkDog> = ["Rex", 48];
Enter fullscreen mode Exit fullscreen mode

4. 使用 Setter 和 Getter

Setter 和 Getter 也存在于纯 JavaScript 中。不过,它们在 TypeScript(以及其他语言)中非常有用。

class Dog{
   private _name: string = "";

   get name(): string{
      return this._name;
   }

   /** Check the length of the name before setting it **/
   set name(newName: string){
      if(newName.length < 8) {
         throw new Error(`The dog's name needs at least 8 charachters`)
      }

      this._name = newName;
   }
}
Enter fullscreen mode Exit fullscreen mode

5. 可选链式调用

可选链最近已添加到 JavaScript(ECMAScript 2020)。

let cat?: ICat;  

/** With optional chaining **/
let animal = cat?.fur.length;

/** Without optional chaining **/
let cat = cat === null || cat === undefined ? undefined : car.fur.length;
Enter fullscreen mode Exit fullscreen mode
文章来源:https://dev.to/basilebong/5-useful-typescript-tricks-419i
PREV
Amazona 第一部分:构建类似亚马逊的电商网站
NEXT
数据库新手入门:理论方法