自动编译
tsc --init 生成tsconfig.json
修改outDir地址
点击终端—>运行任务—>监视typescript
或
安装ts-node ts-node xxx.ts
数据类型
const count: number = 1
声明同时声明类型 继承Number上所有方法
// 对象类型
const person: {
name: string,
age: number
} = {
name: 'ming',
age: 12
}
必须有name属性 age属性可选 [propName: string]: any 任意属性
let c: {name: string,age?: number,[propName: string]: any} = { name: ‘aaa’, age: 18,b: 11}
// 数组类型
let arr: string [] = [‘11’,‘22’]
let arr: Array = [1,2,3]
class Person {}
const person1: Person = new Person()
//函数类型
const fn: () => String = () => {
return '必须返回String类型'
}
函数返回类型
function getTotal(one: number, two: number) : number{
return one + two
}
const total = getTotal(1,2)
console.log(total);
类型断言
告诉解析器变量的实际类型
s = e as string 变量 as 类型
s = e <类型>变量
数组注解
//定义数值数组
const numArr :number [] = [1,2,3]
//定义字符串数组
const strArr :string [] = [‘a’,‘b’,‘c’]
//定义undefined数组
const undefinedArr :undefined [] = [undefined,undefined]
//定义字符、数值、undefined混合数组
const arr :(string | number | undefined) [] = [1,2,‘3’,undefined]
//定义对象数组
const objArr1 :{name: string, age: number} [] = [{
name: 'ming',
age: 18
}]
// 类型别名
type Lady = {name: string, age: number}
const objArr2 :Lady [] = [{
name: 'ming',
age: 19
}]
class Madam {
name: string;
age: number
}
const objArr3 :Madam [] = [{
name: 'hong',
age: 20
}]
元组
const arr1 :[string,string,number] = [‘zhang’,‘teacher’,28]
// 类型必须一一对应
const arr2 :[string,string,number][] = [
\['zhang','teacher',28\],
\['zhang','teacher',22\],
\['zhang','teacher',21\],
]