[ 基础用法 ]
let str: string = 'hello world'
console.log(str)
const arr: number[] = [1, 2, 3]
const result = arr.find(i => i > 2) as number | undefined
result
? console.log(result)
: console.log('not find')
// 声明了元素类型后,数组存储指定类型的元素
let arr1: number[]
let arr2: Array<string>
// 元组可以定义简单的多类型元素组成的数组
// 元组在一定程度上限定了内部元素的数量
let arr3: [number, string, boolean?] = [1, 'mary', false]
let arr4: [number, string, boolean?] = [1, 'mary']
enum e {
A, B, C
}
console.log(e.A) // 0
console.log(e[0]) // A
- void 当函数没有返回值的时候,断言用 void
- Function 函数断言的 undefined 可以写成 void
function add(a:number = 0, b:number = 0):number | void{
return (a + b) || undefined
}
console.log(add(1, 2))
interface Obj {
name: string,
age: number
}
const obj: Obj = {
name: 'jsck',
age: 20
}
type List = number[] | null
let list:List = null
list = [1,2,3]
type Person = {name: string, age: number}
const p = {name: 'jack', age: 20}
- 泛型,可以在调用的时候在传入实际类型声明
- 泛型和继承配合使用可以提高代码效率
- 泛型声明了所继承的类后,就可以调用共同父类的属性和方法来实现代码复用了。
class PP {
constructor(
protected name: string = 'PP'
) {}
public say() {
console.log(this.name)
}
}
class PPA extends PP {
constructor(
protected age: number = 12
) {
super('ppa')
}
}
class PPB extends PP {
constructor(
protected need: boolean = true
) {
super('ppb')
}
}
const ppa = new PPA()
const ppb = new PPB()
function sayName<T extends PP>(pp: T): void {
pp.say()
}
sayName(ppa)
sayName(ppb)
// 这里实际上隐形的使用了泛型
function sayname(pp: PP): void {
pp.say()
}
sayname(ppa)
sayname(ppb)
[ 配置文件 ]
// tsconfig.json
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"rootDir": "./src", // 开发文件根目录
"moduleResolution": "node",
"baseUrl": "./", // 项目文件根目录
"paths": { // alias
"@/*": [
"src/*"
]
},
"typeRoots": ["./src/types"], // 配置类型文件位置,用于全局引入
"outDir": "./dist", // 配置 build 输出目录
}
}
[ 配置类型文件 ]
interface Obj {
name: string,
age: number
}
interface OBJ {
new(name: string, age: number): any
}
interface Model {
render(): void
}
[ 常见问题 ]
[ string 类型不能用作索引 ]
img.src = tank[k as keyof typeof tank]