TS初学

//1、类型推断  不建议使用
let str = 'abc'
str = '123'
//console.log(str)
//2、类型注释
let str1:string = "abc"
str1 = 'ewer'
//console.log(str1)
//3、类型断言
let str2:string
str2 = '1234'
//console.log(str2)
let numArr = [1,2,3]
const result = numArr.find(item => item>1) as number
console.log(result * 5)
//4、基础类型和联合类型
let v1:string = 'abc'
let v2:number = 123
let v3:boolean = true
let nu:null=null
let un:undefined=undefined
let v4:string | null = null
let v5:1 | 2 | 3 = 3
//5、数组、元组、枚举
let arr = [1,2,4,'123']  //不推荐
let arr1:number[] = [1,2,3]
let arr2:Array<string> = ["a","b","c"]
let t1:[number,string,number] = [1,'a',2]
t1[0] = 4
console.log(t1)
//问号的使用  代表这个值可选  可有可无
let t2:[number,string,number?] = [1,'a',2]
                                            //枚举类型                                        
enum MyEnum {A,B,C} 
console.log(MyEnum.A)
console.log(MyEnum[0])
//6、Void类型  只能分配undefined 这个值,通常在函数的时候使用
function MyFn (a:number,b:number):number {
    return 100
}
function MyFn1 (a:number,b?:number):number {
    return 100
}
function MyFn2 (a=10,b:string,c?:boolean,...rest:number[]):number {
    return 100
}
const f = MyFn2(20,'abc',true,1,2,3,4)
console.log(f)
//7、接口
interface Obj {  //避免声明数据的时候有数据偏差
    name:string,
    age:number
}
const obj:Obj = {
    name:'123',
    age:123 
}
//8、类型别名
let a:string|number=10    
type MyUserName = string|number
let a1:MyUserName = 'abc'
//9、泛型
function MyFn3 (a:number,b:number):number[]{
    return [a,b]
}
// T是一个变量名  任何一个都可以
function MyFn4<T> (a:T,b:T): T[]{
    return [a,b]
}
MyFn4<number>(1,2)
MyFn4<string>('1','3')
MyFn4("a","n")
MyFn4(5,6)     

 

posted @ 2024-01-18 14:17  maplethefox  阅读(5)  评论(0编辑  收藏  举报