TS中的关键字总结

is

is 类型保护,用于判断类型的函数中做类型限制

// bad
function isString(value: unknown): boolean{
  return typeof value === "string";
}

//good
function isString(value: unknown): value is string{
  return typeof value === "string";
}

in

in 其实就像是遍历一样

type Keys = 'a' | 'b' | 'c';
type obj = { 
    [ T in Keys]: string;
}
// in 遍历 Keys,并为每个值赋予 string 类型
 
// type Obj = {
//     a: string,
//     b: string,
//     c: string
// }

keyof

keyof 可以获取一个对象接口的所有 key值

type obj = { a: string; b: string }
type Foo = keyof obj;
// type Foo = 'a' | 'b';

typeof

typeof 用于获取某个变量的具体类型

const obj = { a: '1' };
type Foo = typeof obj; 
// type Foo = { a: string }

extends、implements

  • extends用于接口与接口、类与类、接口与类之间的继承
  • implements用于类与类、类与接口之间的实现
    注意: extends类似于es6的extends,implements没有继承效果的,但是要求子类上必须需有父类的属性和方法,更倾向于限制子类的结构!

type、interface

type 类型别名 用于给类型起一个新名字
type Value: string = "111"
// 或
type Iprops = {
  value: string,
  getName: () => string
}
interface 接口 用于声明类型
interface MyInterface {
  value: string,
  getName: () => string
}
type 和 interface的区别
  • type可以定义单个变量类型、联合类型、对象,interface只能定义对象;
  • type不可以重复声明,interface可以重复声明(声明合并);

    type Iprops = {
    name: string
    age: number
    }
    type Iprops:string = "111" // Error 标识符“Iprops”重复。ts(2300)
    
    interface MyInterface {
    name: string
    age: number
    }
    interface MyInterface {
    gender: string
    }
    const obj: MyInterface= {
    name: "string"
    age: 18,
    gender: "男",
    }
    // 重复声明相当于把两个类型加一块

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值