Javascript

typesscript基础到vue项目中的使用

本文主要是介绍typesscript基础到vue项目中的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

typescript类型

// 布尔
let boo: boolean = true;
boo = 111; //报错

//数字
let num: number = 111;

//字符串
let str: string = "aaa";

//数组
let arr: Array<number> = [1, 2, 3];
let arr2: string[] = ["a", "b"];
let arr3: Array<string> = ["a", "b"];

//undefined null
let _undefined: undefined = undefined;
let _null: null = null;

//ts中的或
let some_var: number | string | boolean = 123;
some_var = "aaa";
some_var = true;
//any 不在进行类型校验
let any_var: any = 123;
any_var = true;

//void 没有return
function func(arg: number): void {}
func(111);
function fun2(arg: string): boolean {
  return true;
}

//对象 使用接口来定义对象的类型
// interface
interface IPerson {
  name: string;
  age: number;
  sex: string;
}
let obj: IPerson = {
  name: "张三",
  age: 20,
  sex: "男",
};
let obj2: IPerson2 = {}; //定义空对象会报错 必须使用?定义可选项
//可选项
interface IPerson2 {
  name?: string;
  age?: number;
  sex?: string;
}

//接口继承
interface IA extends IPerson {
  hobby: Array<string>;
}
let person2: IA = {
  name: "李四",
  age: 24,
  sex: "男",
  hobby: ["打球"],
};

//继承多个
interface IB {
  name: string;
}
interface IC {
  age: number;
}
interface ID extends IB, IC {
  sex: string;
}
let person3: ID = {
  name: "王二",
  age: 25,
  sex: "女",
};
// ts 中的与 类似继承
let person4: IB & IC & ID = {
  name: "王二",
  age: 25,
  sex: "女",
};
// 不确定的属性名
interface IPerson3 {
  [proName: string]: any;
}
let person5: IPerson3 = {};
let person6: IPerson3 = {
  a: 1,
  b: true,
};

// implements 接口实现
interface IPerson4 {
  name: string;
  age: number;
  sex: string;
  getName: () => string;
  getAge(): number;
}
class Person implements IPerson4 {
  name: string = "张三";
  age: number = 20;
  sex: string;
  getName(): string {
    return this.name;
  }
  getAge(): number {
    return this.age;
  }
  //实现自己的方法
  sayHello(): void {}
}

//类型断言
function getLength(str: number | string): number {
  if ((str as string).length) {
    // return (str as string).length
    return (<string>str).length
  }else{
    str.toString().length
  }
}
//非空断言
function func3(arg?:string):number {
 return arg!.length 
}
func3()

// 枚举
enum Color{
  red,
  green,
  yellow
}
// 属性的值从0开始自增
Color.red //0
Color.green//1
Color.yellow //2
//反向映射
console.log(Color[0]) //red
// {
//   red:0,
//   green:1,
//   yellow:2
//   0:'red',
//   1:'green',
//   2:'yellow'
// }
//给枚举赋值
enum Color2{
  red, //1
  green=2,//2  
  //如果green=abc 如果前一个枚举值是字符串 后一个枚举值必须赋值
  yellow //3
}

//泛型
function func4<T>(arg:T):void{

}
func4<number>(123)
func4<string>('abc')

这篇关于typesscript基础到vue项目中的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!