typescript 工具安装
npm install -g typescript
tsc main.ts
调用 tsc 可以将 ts文件编译为 js文件
tsc --init # 生成配置文件
最好将 tsconfig.json 的 strict修改为 false关闭严格模式
console.log('hello world')
function greet(person: string, date: string) {
console.log(person, date)
}
greet("end ", "game")
设置语法 为 es5版本
typescript 可以自由配置对语法检查的程度,可以严格,可以宽松
基础类型
数组类型
//数组 type[] 或者 Array<type>
let arr: number[] = [1, 2, 3]
let arr2: Array<number> = [1, 23,]
console.log(arr2)
联合类型
const names = ['1', '2', 'sa']
names.forEach(el => {
console.log(el.toUpperCase())
})
function printRecord(pt: { x: number, y?: number | string | string[] }) {
console.log('pt.y typeof is ', typeof pt.y)
console.log('record', pt)
if (typeof pt.y === 'string') {
} else if (typeof pt.y === 'number') {
} else if (Array.isArray(pt.y)) {
console.log(pt.y.join(','))
} else {
console.log('other type')
}
}
printRecord({ x: 1, y: "222" })
类型别名 type 和 interface 来定义类型
这一部分 很像 golang的语法
用type 来定义 类型别名
// 使用 type关键字 定义类型
type S = number | string | string[] | number[]
type Point = {
x: number
y: string[] | number[] | string
}
function printPoint(x: Point) {
console.log(x)
}
printPoint({ x: 1, y: [1, 2, 3] })
type UserInputString = string
function sanitizedInput(str: string): UserInputString {
return str.slice(0, 2)
}
let escapedString = sanitizedInput("hello world")
console.log(escapedString)
// 使用 interface 来定义接口
interface Var {
x: number
y: number | number[] | string | string[]
}
function printVar(v: Var) {
console.log(v)
}
printVar({
x: 1,
y: [1, 2, 3, 3, 4]
})
interface Animal {
name: string
}
// bear继承了 animal类
interface Bear extends Animal {
honey: boolean
}
const bear: Bear = {
honey: true,
name: "bear"
}
console.log(bear)
type Bird = Animal & {
fish: string
}
var bird: Bird = { fish: "fish", name: "bird." }
console.log(bird)
类型断言语法
// 类型断言语法:
// const dom = document.getElementById('main_canvas') as HTMLCanvasElement
// const dom2 = <HTMLCanvasElement>document.getElementById('main_canvas')
// console.log(dom)
const x = ('hello' as any) as number
console.log(x)
文字类型的用法
这个写法有点像枚举【很多情况下 应该是用于代码提示】
// 类型断言语法:
let x: 'hello' = 'hello'
function printText(s: string, alignment: 'left' | 'right' | 'center') {
console.log(`${s} is ${alignment}`)
}
printText("str", 'left')
//编译会报红线
// printText('str', 'uuu')
// 实现一个比较函数
function compare(a: string, b: string): -1 | 0 | 1 {
return a === b ? 0 : a > b ? -1 : 1
}
console.log(compare("hello", "world"))
interface Options {
width: number | string
}
function configure(x: Options | 'auto') {
console.log('option', x)
}
configure({
width: '650px'
})
configure('auto')
//使用文字类型推导
const req = {
url: 'https://www.baidu.com',
method: 'GET'
} as const
function handleRequest(url: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE') {
}
handleRequest(req.url, req.method)
null 和 undefined类型
let x: undefined = undefined
let y: null = null
let z: string = undefined
console.log(z)
function doSomething(x: string | null) {
if (x === null) {
} else {
console.log(x.toUpperCase())
}
}
function liveDangerously(x?: number | null) {
// ! 能确保 绝对不是 null
console.log(x.toFixed())
console.log(x!.toFixed())
}
// liveDangerously(null)
liveDangerously(6666)
enum 枚举类型
enum Direction {
up = 1,
down,
left,
right,
}
console.log(Direction.down)
bigint 和 symbol
enum Direction {
up = 1,
down,
left,
right,
}
console.log(Direction.down)
类型缩小
// 类型守卫
var strs = "hello world"
console.log(typeof strs == "string")
function printAll(strs: string | string[] | null) {
if (typeof strs === 'object') {
} else if (typeof strs == 'string') {
} else {
}
}
泛型函数
//泛型函数
function longest<Type extends { length: number }>(a: Type, b: Type): Type {
return a.length >= b.length ? a : b
}
const longArray = longest([1, 2], [1, 2, 3, 3])
const longString = longest("aaa", "bbbbbb")
console.log(longArray, longString)
可选参数
// 可选参数
function f(x: number, y: string = "default strings...") {
console.log(x, y)
}
f(1, "hello world")
f(122)
function myForEach(arr: any[], callback: (el: any, index?: number) => void) {
arr.forEach(callback)
}
myForEach([1, 2, 3], (el, idx) => {
console.log(el, '...', idx)
})
myForEach([1, 2, 3], el => {
console.log('el = ', el)
})