typeScript是JavaScript的超集,浏览器是无法识别ts的,需要编译成js使用。
typeScript 可以进行严格的类型检查
官方文档 :https://www.tslang.cn/docs/release-notes/typescript-3.1.html
TS的安装:
//2.1 布尔类型
let flag: boolean = false
console.log(flag) //false
//2.2 数字类型
let num: number = 100
console.log(num) //100
// 2.3 字符串
// 明确定义一个变量str
let str: string = '123'
console.log(str) //123
// 2.4 数组
let arr = [1, 2, 3, 'q']
let arr2: number[] = [1, 4, 7]
let arr3: (string | number)[] = [1, 5, 9]
console.log(arr) //[1, 2, 3, 'q']
console.log(arr2) //[1, 4, 7]
console.log(arr3) //[1, 5, 9]
// 2.5 any
// 任意类型,在我们不需要ts做类型检测的时候使用
// 不检查这个类型的使用方法,也不检测他拥有的属性
let noMatch: any = 4
noMatch.push
// 2.6 unknow
// 任意类型,在我们不需要ts做类型检测的时候使用
// 但是会限制类型的使用方法
// (理论上)某一个对象单独使用的方法大家都有的方法就可以通过unknown的检测,但凡有一个是别人没有的
// 就不通过
// 2.7 断言
// 我告诉ts,我比你更清楚这个数据是什么数据类型,所以你听我的就行,你别管了
// 方式1
var noMatch: unknown = [1, 2];
(noMatch as number[]).push(2)
console.log(noMatch)
// 2.8 void
// 与any相反,表示没有任何类型
// 一般用在函数没有返回值的时候,设置返回值void
function fn(): void {
console.log('海绵宝宝')
return 1
}
let a = fn()
console.log(a) // 1
// 2.9 联合类型
let type: string | boolean | number = 1
// type = true
type++
console.log(type.toString())
// 3 函数
// js的函数有两种类型 声明式函数 赋值式函数
// 3.1 声明式函数
function a(num1: number, num2: number): void {
console.log(num1 + num2)
}
a(1, 2)
// 3.2 赋值式函数
const year = function (num1: string, num2: number): string {
return num1 + num2
}
//const year = function (num1: number, num2: number): number{
// return num1 + num2
// }
console.log(b(10,20)) //30
// 3.3 完整的函数类型定义
let year: (a: number, b: number, c: number) => void = function (c: number, d: number, e: number): void {
console.log(c + d + e)
}
year(2, 9, 99) //110
// 3.4 函数的可选参数
// 传递给一个函数的参数个数必须与期望的个数一直
// 但是我们可以使用一个?来string实现可选参数的功能
// 可选参数要放在最后面
let year: (a: number, b: number, c?: number) => void = function (c: number, d: number, e?: number): void {
console.log(c + d)
console.log(e)
}
year(2, 9, 99)
// 3.5 函数的参数默认值
let year = function (d: number = 80, c: number): void {
console.log(c + d)
}
year(undefined, 2)
// let year = function (c: number,d: number = 80): void {
// console.log(c + d)
// }
// year(2)