参考链接 www.tslang.cn/docs/handbo… www.tslang.cn/play/index.…
any 在编程阶段还不清楚类型的变量指定一个类型
let notSure: any = 4
notSure = 'maybe a string instead'
notSure = false // okay, definitely a boolean
let list: any[] = [1, true, 'free']
list[1] = 100
void 当一个函数没有返回值时或者返回值为undefined,你通常会见到其返回值类型是 void
function warnUser(): void {
console.log('This is my warning message')
}
类型断言 as
- 类型断言好比其它语言里的类型转换,但是不进行特殊的数据检查和解构
let someValue: any = 'a string'
// 虽然 someValue 初始值是 string类型,但是 as 为number,也会跳过检查,不会报错
let strLength: number = someValue as number
console.log(strLength)
someValue = '99'
// '99'
console.log(someValue)
联合类型| 可选? 非空断言!
- 我们用竖线( |)分隔每个类型,所以 number | string | boolean 表示一个值可以是 number, string,或 boolean。
function padLeft(value: string, padding: string | number) {
// ...
}
let indentedString = padLeft('Hello world', 12)
- ? 可选参数 可选属性
function buildName(firstName: string, lastName?: string) {
if (lastName) return firstName + ' ' + lastName
else return firstName
}
let result1 = buildName('Bob') // works correctly now
let result2 = buildName('Bob', 'll') // works correctly now
interface Person {
name: string
age?: number // age is an optional property
}
const p1: Person = { name: 'bwf' }
const p2: Person = { name: 'bwf', age: 12 }
- ! 来断言 变量 不是 null 或 undefined
interface Person {
name: string
age: number | undefined // age 是一个可空属性
}
function getPersonAge(person: Person): string {
return person.age!.toString() // 使用 "!" 来断言 age 不是 null 或 undefined
}
const person: Person = { name: 'Alice', age: undefined }
console.log(getPersonAge(person)) // 抛出运行时错误
any unknow区别
any类型可以接受任何类型的值,并绕过类型检查,开发者需要自行确保类型安全。
unknown类型也可以接受任何类型的值,但是必须在使用前进行类型检查或类型断言,提供了更好的类型安全性。推荐在类型不确定的情况下使用unknown类型,而避免滥用any类型。
any类型的变量可以赋值给任何类型的变量。
let value: any;
value = 10; // 可以赋值为数字
value = "hello"; // 可以赋值为字符串
value = true; // 可以赋值为布尔值
// 以下编译时不会报错,仅在运行时报错
console.log(value.toUpperCase());
let value: unknow;
value = 10; // 可以赋值为数字
value = "hello"; // 可以赋值为字符串
value = true; // 可以赋值为布尔值
// 以下编译时会报错,运行时也会报错 只有
console.log(value.toUpperCase());
let value: unknown;`unknown`类型也可以接受任何类型的值,但是必须在使用前进行类型检查或类型断言,提供了更好的类型安全性。推荐在类型不确定的情况下使用`unknown`类型,而避免滥用`any`类型。
value = 10; // 可以赋值为数字
value = "hello"; // 可以赋值为字符串
value = true; // 可以赋值为布尔值
// 以下编译时不会报错,运行时报错
if (typeof value === "string") {
console.log(value.toUpperCase());
}
// `any`类型的变量可以赋值给任何类型的变量
let a: any
a = 9
let b: string
b = a
console.log('b', b) // 9
let a: unknown
a = 9
let b: string
b = a // 不能将类型“unknown”分配给类型“string”。
// 以上可通过断言 或者 类型判断方式解决
let a: unknown
a = 9
let b: string
b = a as string
console.log('b', b)
never 和 void 区别
void类型表示函数没有返回值,或者说函数返回的是undefined。在其他情况下,变量的类型为void时,只能赋值为undefined或null。
在函数中,当函数的返回类型被推断为never时,通常意味着函数内部有一些无法到达的代码分支,或者函数总是会抛出异常。
function throwError(message: string): never {
throw new Error(message);
}
function greet(): void {
console.log("Hello!");
}
const result: void = undefined;
声明对象类型
- 字面量
let person: { name: string; age?: number; [key: string]: any }
person = { name: 'bwf', age: 12, id: 113, city: '工作' }
console.log('person', person)
声明函数
- 字面量
let getTotal: (a: number, b: number) => number
getTotal = (x, y) => x + y
console.log('total', getTotal(1, 3))
声明数组类型
let arr: string[]
arr = ['1', '3']
元祖
let arr1: [string, number?]
arr1 = ['1', 2]
let arr2: [number, ...string[]]
arr2 = [2, '1', '4']
console.log('arr2', arr2)
枚举 enum
数字枚举(具有反向映射)
- 采用手动赋值
enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green;
// 2
console.log(c)
- 可以由枚举的值得到它的名字
enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];
// 'Green'
console.log(colorName);
字符串枚举
enum Direction {
Up = 'up',
Down = 'down',
Left = 'left',
Right = 'right'
}
console.log(Direction, Direction.Up) // {Up: 'up', Down: 'down', Left: 'left', Right: 'right'} 'up'
</script>
type 类型别名 联合类型| 交叉类型&
type MyString = string
type MyStringOrNumber = string | number
type MyArray = Array<any>
type Person = {
name: string
age: number
id?: string
sayHello(): void
}
type MyAddFunction = (x: number, y: number) => number
let a: MyString = '12'
let b: MyStringOrNumber = 12
b = '123'
let list: MyArray = [1, 2, '33']
type StatusCode = '0' | '1' | '2'
const codesHandler = (code: StatusCode) => {
console.log(code)
}
codesHandler('2')
const p: Person = {
name: 'bwf',
age: 12,
sayHello() {
console.log('say')
}
}
p.sayHello()
p.id = '132'
let fun: MyAddFunction = (x, y) => {
return x + y
}
fun(1, 3)
type UserType = {
name: String
age: number
id: String
}
type CheckedType = {
code: string
isChecked: boolean
}
type RowType = UserType & CheckedType
const row: RowType = {
name: 'bwf',
age: 12,
id: '113',
code: '12',
isChecked: true
}
console.log('row', row)
类
// 属性和构造器内部属性赋值的简写
class Person {
constructor(
private name: string,
private age: number
) {}
}
const p = new Person('bwf', 12)
console.log('p', p)
属性修饰符
- public 类内部、子类、实例访问
- protected 类内部、子类访问
- private 类内部访问
- readonly 属性无法被修改
抽象类,无法被new实例化,允许继承,有抽象方法+具体方法。定义通用接口,确保关键实现,共享代码和逻辑。
abstract class Package {
constructor(protected weight: number) {}
// 定义通用接口
abstract calculate(): number
// 提供公用的逻辑
printPackage() {
console.log(`重量:${this.weight},运费为:${this.calculate()}`)
}
}
class CommonPackage extends Package {
constructor(
weight: number,
private price: number
) {
super(weight)
}
// 子类必须实现父类的抽象方法
calculate(): number {
return this.weight * this.price
}
}
const cp = new CommonPackage(10, 5)
cp.printPackage() // 重量:10,运费为:50
接口interface 定义格式,不能有任何具体实现
- 接口去约束类
interface IPerson {
name: string
age: number
speack(): void
}
class Person implements IPerson {
constructor(
public name: string,
public age: number
) {}
speack(): void {
console.log(`我叫${this.name},今年${this.age}岁`)
}
}
const p = new Person('bwf', 12)
p.speack()
- 接口去约束对象
interface IPerson {
name: string
age?: number
readonly gender: string
speack(): void
}
const person: IPerson = {
name: '',
age: 0,
speack() {
console.log(`我叫${this.name},今年${this.age}岁`)
},
gender: '男'
}
person.name = 'wmy'
- 接口之间可以继承
interface vs type
- 相同点:interface和type都可以定义对象结构
不同点
- interface专注于类和对象的结构,可以继承;
- type定义类型别名(包含基础类型)、联合类型、交叉类型
interface vs 抽象类
- 相同点:interface和type都可以定义类的格式
不同点
- 接口只能描述结构,不能有任何实现代码,一个类可以实现多个接口。
- 抽象类:既有抽象方法又有具体实现。一个类只能继承一个抽象类。
泛型
- 泛型函数
function log<T,>(data: T): void {
console.log('data', data)
}
log('haha')
log<boolean>(true)
- 泛型接口
interface IPerson<T> {
name: string
age?: number
readonly gender: string
speack(): void
other?: T
}
type OtherInfoType = {
address: string
tel: string
}
const person: IPerson<OtherInfoType> = {
name: '',
age: 0,
speack() {
console.log(`我叫${this.name},今年${this.age}岁`)
},
gender: '男',
other: {
address: 'bb',
tel: '188'
}
}
- 泛型类