Ts的常用特性总结

166 阅读2分钟

“开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 6 天,点击查看活动详情

1.数据类型

javeScript的数据类型有 字符串类型,数字类型,布尔类型,null,undefined,对象,数组 typeScript 新增的类型有:联合类型,自定义类型,接口,元组,字面量类型,枚举,void,any

2.枚举类型

enum枚举:枚举可以理解为常量的集合

 enum direction={
 top,//如果不赋值默认为0
 down,
 left,
 right
 }
 //使用
 let a=direction.a
 

3.type,interface

定义接口

interface User{
    name:string,
    age:number,
    like:string
}

定义类型别名

type User = {
 name:string,
 age:number,
}

3.联合类型,交叉类型

联合类型:一次只能使用一种类型,类似或的逻辑

interface A={
name:string,
age:number
}
interface B={
like:string
}
let type C= A|B

交叉类型:每次都是多个类型的合并类型,类似且的逻辑 ---- &

interface A={
name:string,
age:number
}
interface B={
like:string
}
let type C= A & B

var s:a= {
    name:'张三'
    age: 16,
    like:’apple‘
}

4.typeof

typeof:操作符可以用来获取一个变量声明或对象的类型

function toArray(x: number): Array<number>{
  return [x]
}
type Func = typeof toArray //(x: number) => nubmer[]

5.keyof

获取对象中所有的key值

interface User {
  name: string;
  age: number;
}
type k1 = keyof User; //"name" | "age"

6.in:用来遍历枚举类型

type A = "a" | "b" | "c"
type B =  { 
[p in A]: any 
} 
结果:
{ a: any, b: any, c: any }

7.Paritial 将某个类型里的属性全部变为可选项 ?

interface User { name: string ,age:number}
type User1 = Partial<User> 
//结果
{ 
name?: string ,
age?:number
}

8.Reuqired 将某个类型里的属性全部变为必选项

interface User{
name?:string,
age?:number
}
type User2=Reuqired<User>
//结果
{
name:string,
age:number
}

9.Readonly 将某个类型所有属性变为只读属性,不能被赋值

interface User { name: string }
type User1 = Readonly<User>
const c:User1 = { name: "zz" }
c.name = '22' // 报错

10.Exclude 将某个类型中属于另一个的类型移除掉

type A = Exclude<"a" | "b" | "c", "a"> // "b" | "c"
type B = Exclude<"a" | "b" | "c", "a" | "b"> // "c"

结束语

希望大家能够喜欢我的文章,我真的很用心在写,也希望通过文章认识更多志同道合的朋友。

最后伙伴们,如果喜欢我的可以给点一个小小的赞👍或者关注➕都是对我最大的支持。