let str1 = 'str1' //类型推断
let str2: string = 'str2' //类型注解
let arr1 = [1, 2, 3]
let ans = arr1.find(x => x > 2) as number //类型断言
console.log(ans*3,'ans*3'); //9 ans*3
let a1:string|number =3 //联合类型
let a2: 1 | 2 | 3 = 3
//数组
let arr2: number[] = [1, 2, 3]
let arr3: Array<string> = ['a', 'b', 'c']
//元组
let tuple1: [number, string] = [1, 'a']
let tuple2: [number, string, boolean?] = [1,'a'] //问号代表可选
//函数
function sum(a:number,b:number):number{
return a+b
}
console.log(sum(1, 2), 'sum'); //3 sum
//接口
interface obj1{
name: string,
age: number
}
let obj2: obj1 = {
name: 'obj2',
age: 2
}
//类型别名
type type1 = string | number
let a3: type1 = 'a3'
//泛型
function fn1<T>(a: T, b: T): T[]{
return [a, b]
}
console.log(fn1<number>(1, 2), 'fn1'); //[1,2] fn1
typescript初学
于 2023-09-24 04:08:52 首次发布