记录部分常见的语法关键字及其简单说明、用法
语法、关键字
类型断言/转换 as语法
在值的后面使用 as Type 明确指定某个值的具体类型
// as
let asRoot = document.getElementById('root') // asRoot: HTMLElement | null
let asRoot1 = document.getElementById('root') as HTMLElement // asRoot1: HTMLElement
// 定义一个常量字面量
const Colors = {
Red: 'red',
White: 'white'
} as const
! 尾语法
从前面的表达式里移除 null 和 undefined
// !
let root1 = document.getElementById('root')! // root1: HTMLElement
extends 关键字
含义
- 继承/拓展的含义 - 约束 - 分配
继承父类的方法和属性(js)
通过extends
继承后者(父类)的属性、方法
class Animal {
kind = 'animal'
constructor(kind: string) {
this.kind = kind
}
sayHello() {
console.log(`Hello, I am a ${this.kind}`)
}
}
class Dog extends Animal {
constructor(kind: string) { super(kind) }
bark() {
console.log('wang wang')
}
}
const dog = new Dog('dog')
dog.bark() // wang wang
dog.sayHello() // Hello, I am a dog
继承/拓展类型
通过extends
继承后者(父类型)的属性定义
// extends 关键字 继承/拓展类型
interface Animal1 {
kind: string
}
interface Dog1 extends Animal1 {
bark: () => void
}
// Dog1: { kind:string, bark: () => void }
const dog1: Dog1 = { kind: 'dog', bark: () => { } }
泛型约束
对传入的参数进行一定的限制
// extends 关键字 泛型约束
function getIds<T extends { id: string | number }>(list: T[]) {
if (!list || !list.length) return []
return list.map(it => it.id)
}
interface TItem { id: string | number, [propName: string]: unknown }
let list: TItem[] = [{ a: 1, id: 1 }]
let ids = getIds(list)
console.log(' ====> ids', ids);
条件类型与高阶类型
SomeType extends OtherType ? TypeTrue : TypeFalse
大致意思是:类型 SomeType 是否可以分配给 OtherType,而不是说SomeType是OtherType的子集。
type TypeName<T> =
T extends string ? string :
T extends number ? number :
T extends boolean ? boolean :
T extends undefined ? undefined :
T extends Function ? Function :
T extends Array<any> ? T :
object
type TN1 = TypeName<string> // TN1 = string
type TN2 = TypeName<[]> // TN2 = any[]
type TN3 = TypeName<string[]> // TN2 = string[]
let tn3: TN3 = ['d']
let tn4: string extends TN1 ? TN1 : number = '1' // tn4: string
keyof
主要同于类型推导
访问动态类型
// 这里表达的含义: 参数key 是 T中的属性名称类型之一
function getProps<T>(item: T, key: keyof T) {
return item[key] === undefined ? '--' : item[key]
}
let list1: object[] = []
let res = list1.map((item: object) => {
return { ...item }
})
// let res = ([] as object[]).map((item: object) => {
// return { ...item }
// })
getProps({ name: 2 }, 'name') // 2
typeof
获取一个变量的类型并且能够用来声明新的变量
const Colors1 = { red: 'red', blue: 'blue' }
function getColorProp(key: keyof typeof Colors1) {
return Colors1[key]
}
let cRed = getColorProp('red')
type Color2 = keyof typeof Colors1 // type Color2 = "red" | "blue"
in 类型映射
//in 类型映射
type A = { age: number, id: string }
type User = {
[K in keyof A]: string
// c: string @errors 映射的类型可能不声明属性或方法。ts(7061) 应该使用 交叉类型 & { c: string }
} & { f: string }