在官网的页页https://www.typescriptlang.org/可以调试。
#类型推断
let str: string = 'abc'
let str1: string
str1='a'
#数组及类型断言
let numArr = [1, 2, 3]
const result = numArr.find(item => item >2) as number
result * 5
#基础类型和联合类
let v1: string = 'abc'
let v2: number = 10
let v3: boolean = true
let nu: null = null
let un: undefined = undefined
let v4: string | null = null;
let v5: 1 | 2 |3 = 2
#数组、元组、枚举
let arr: number[] = [1, 2, 3]
let arr1: Array<string> = ['a','b','c']
/*元组*/
let t1: [number,string,number] = [1,'a',2]
t1[0]=1
let t2: [number,string,number? ] = [1,'a']
/*枚举*/
/*下面其实是键、值共6个
A 0
B 1
C 2
*/
enum MyEnum {
A,
B,
C
}
console.log("=====================")
console.log(MyEnum[0])
console.log("---------------------")
console.log(MyEnum.A)
console.log(MyEnum.B)
console.log(MyEnum.C)
[LOG]: "====================="
[LOG]: "A"
[LOG]: "---------------------"
[LOG]: 0
[LOG]: 1
[LOG]: 2
/*编译成js*/
"use strict";
var MyEnum;
(function (MyEnum) {
MyEnum[MyEnum["A"] = 0] = "A";
MyEnum[MyEnum["B"] = 1] = "B";
MyEnum[MyEnum["C"] = 2] = "C";
})(MyEnum || (MyEnum = {}));
console.log("=====================");
console.log(MyEnum[0]);
console.log("---------------------");
console.log(MyEnum.A);
console.log(MyEnum.B);
console.log(MyEnum.C);
#函数、参数
function MyFn (a:number ,b: number) :number {
return a+b
}
function MyFn2 (a:number ,b: string ) : void {
let x:number = 100
}
function MyFn3 (a = 10 ,b: string ,c?:boolean,...rest: number[]) : number {
return 100
}
const f = MyFn3(20,'abc',true,1,2,3,4,5,6)
#接口
interface Obj {
name: string,
age: number
}
const obj:Obj = {
name:"a",
age:10
}
const obj2:Obj = {
name:"b",
age:11
}
#类型
let a1: string | number = 10
type MyUserName = string | number
let a: MyUserName = 10
let b: MyUserName = 'abc'
#泛型
function myFn(a: number,b: number): number [] {
return [a,b]
}
function myFn2<T>(a: T,b: T): T [] {
return [a,b]
}
myFn2<number> (1,2)
myFn2<string> ('a','b')
/*类型推断*/
myFn2('a','b')