我如何提高我的 Typescript 技能 #1:Typeguard 和 Type Utils

2025-05-24

我如何提高我的 Typescript 技能 #1:Typeguard 和 Type Utils

我将与我们分享一些提高我的 Typescript 技能的技巧!

类型保护

Typeguard 允许您验证条件块内对象的类型。

interface Fish {
  swim: () => void
}

interface Bird {
  fly: () => void
}

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined
}
Enter fullscreen mode Exit fullscreen mode

根据条件我们可以确定,宠物对象是Fish

为什么以及在何处使用它?

当你需要检查一个对象的类型时,它非常有用。在上面的例子中,typeguardisFish就是这样使用的。

function toto(pet: Fish | Bird) {
  if (isFish(pet)) {
     pet.swim() // At this moment, TS know that pet is `Fish` and no a `Bird`
  }
}


function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined
}
Enter fullscreen mode Exit fullscreen mode

类型this作为函数中的参数

一个小提示,你可以this在这样的函数中输入对象

function toto(this: { a: string }, arg: number) {
  console.log(this.a, arg) // "toto",  55 
}

toto.bind({ a: 'toto' })(55) // Don't forget to bind `this`

Enter fullscreen mode Exit fullscreen mode

实用程序类型

Typescript 允许我们使用实用程序类型,这是一个非常有用的功能!完整列表请访问https://www.typescriptlang.org/docs/handbook/utility-types.html

我将向您展示我使用的常见实用程序类型!

部分的

构造一个类型,将 Type 的所有属性设置为可选。

interface Toto { a: string, b: string }
// Partial type equal to -> interface Partial<Toto> { a?: string, b?: string }

const partialToto: Partial<Toto> = { a: 'a' }
Enter fullscreen mode Exit fullscreen mode

挑选省略

Pick用于从类型中提取一些键以创建新类型。

interface Toto { a: string, b: string }
// Pick type equal to -> interface Pick<Toto, 'a'> { a: string }

const pickToto: Pick<Toto, 'a'> = { a: 'a' }
Enter fullscreen mode Exit fullscreen mode

Omit用于从类型中删除一些键以创建新类型。

interface Toto { a: string, b: string }
// Pick type equal to -> interface Omit<Toto, 'a'> { a: string }

const omitToto: Omit<Toto, 'a'> = { b: 'b' }
Enter fullscreen mode Exit fullscreen mode

使用三种实用类型,您可以创建新的非常智能的类型!并且对其他开发人员理解也非常有用。

记录

您可以使用类型键和类型构造一个对象,并像这样创建有用的类型

type TotoKeys = 'a' | 'b' | 'c'
interface Toto { name: string, age: number }

const toto: Record<TotoKeys, Toto> = {
   a: { name: 'a', age: 55 },
   b: { name: 'b', age: 44 },
   c: { name: 'c', age: 33 },
}
Enter fullscreen mode Exit fullscreen mode

我喜欢记录,因为你可以使用枚举来输入键!

enum TotoEnum { 
  A = 'A',
  B = 'B',
  C = 'C'
}
interface Toto { name: string, age: number }

const toto: Record<TotoEnum, Toto> = {
   [TotoEnum.A]: { name: 'a', age: 55 },
   [TotoEnum.B]: { name: 'b', age: 44 },
   [TotoEnum.C]: { name: 'c', age: 33 },
}
Enter fullscreen mode Exit fullscreen mode

我希望您通过本文学习并提高您的技能!

如果您有其他建议或问题,请随时在下面的评论中提出!


我希望你喜欢这篇文章!

🎁 如果您在TwitterUnderrated skills in javascript, make the difference上关注我并给我点赞,即可免费获得我的新书😁

或者在这里获取

🎁我的新闻通讯

☕️ 你可以支持我的作品🙏

🏃‍♂️ 你可以关注我 👇

🕊 推特:https://twitter.com/code__oz

👨‍💻 Github:https://github.com/Code-Oz

你也可以标记🔖这篇文章!

文章来源:https://dev.to/codeoz/how-i-improve-my-skills-in-typescript-1l91
PREV
利用这些技巧提升你的 JS 技能 #2
NEXT
使用正确的数组方法来提高你的 JS 技能