Typescript高级用法
目录:基础用法应用、类的用法、类型断言、泛型、ts在前端和后端的用法、
基础用法应用
//基本数据类型
export{}
let isDone: boolean = false
let num: number = 123
let hexLiteral: number = 0xf00d
let unusable: void = undefined
function alertName(): void {
console.log('test')
}
function getString(something: string | number): string {
return something.toString()
}
getString('文本')
// getString(123)
enum Days {
Sun = 7,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
}
console.log('🐻', Days['Mon'])
console.log('🐻', Days[8])
interface Person {
readonly id: number
uname?: string
age: number
[proName: string]: any
}
const laoyuan: Person = {
id: 30,
age: 20
}
laoyuan['xx'] = true
类
// 类的使用
/**
* public
* private 只能在本类中使用
* protected 只能在本类和子类中使用
* */
export{}
abstract class Animal {
abstract makeSound(): void
public move(): void {
console.log('动物移动')
}
// private move(): void {
// console.log('动物移动')
// }
// protected move(): void {
// console.log('动物移动')
// }
}
class Dog extends Animal {
constructor() {
super()
}
makeSound() {
console.log('汪汪汪')
}
}
const dog: Dog = new Dog()
dog.makeSound()
dog.move()
//类也能当类型
enum Category {
Fruit,
Vegetable,
Nut,
Seafood,
Dessert
}
let NextId = 0
class FoodData {
id: string
name: string
image: string
category: Category
calories: number
protein: number
fat: number
carbohydrates: number
vitaminC: number
constructor(
name: string,
image: string,
category: Category,
calories: number,
protein: number,
fat: number,
carbohydrates: number,
vitaminC: number
) {
this.id = `${NextId++}`
this.name = name
this.image = image
this.category = category
this.calories = calories
this.protein = protein
this.fat = fat
this.carbohydrates = carbohydrates
this.vitaminC = vitaminC
}
}
let newData: FoodData = new FoodData(
'Tomato',
'app.media.Tomato',
Category.Vegetable,
17,
0.9,
0.2,
3.9,
17.8
)
console.log(newData)
类型断言
// 类型断言
export {}
function getLength(str: string | number): number {
// if((str as string).length)
console.log(<string>str)
if ((<string>str).length) {
return (<string>str).length
} else {
return str.toString().length
}
}
getLength('hiao')
type Name = string
type NameResolver = () => string
type NameOrResolver = Name | NameResolver
function getName(n: NameOrResolver): Name {
if (typeof n === 'string') {
return n
} else {
return n()
}
}
interface A {
msg: string
}
interface A {
age: number
}
function helper(options: A): A {
return options
}
helper({ msg: 'age', age: 123 })
泛型
//泛型类
export{}
interface nameType<T> {
value: T
sayMe: () => T
}
class Name<T> implements nameType<T> {
public value: T
constructor(value) {
this.value = value
}
sayMe() {
console.log(this.value)
return this.value
}
}
var testName = new Name<string>('hello')
testName.sayMe()
var testName2 = new Name<number>(789)
testName2.sayMe()
//泛型约束
export {}
//demo1
interface LengthWise {
length: number
}
//即T就为泛型对象,然后就是T(string类型)必须实现LengthWise这个接口,有length属性
function identity<T extends LengthWise>(age: T): T {
console.log(age.length)
return age
}
//不穿泛型默认就认为identity的类型为string
const result = identity('nihao')
//demo2 keyof是获取接口T的键 "a" | "b" 所以意思是K必须是这两种类型
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key]
}
console.log(getProperty({ a: 1, b: 2 }, 'a'))
//泛型(默认类型)| 泛型接口
//1.泛型默认类型
interface A<T = string> {
value: T
}
const str1: A = { value: '123' }
const str2: A<number> = { value: 123 }
//2. 泛型接口
interface ConfigFn {
<T>(value: T): void
}
const fun: ConfigFn = function <T>(value: T): void {
console.log(value)
}
ts在前后端的用法对比
//前端多用的类型
interface IpriceData {
id: number
message: string
}
type IpriceDataArray = IpriceData[]
function getPriceData() {
return new Promise<IpriceDataArray>((resolve, reject) => {
fetch('url')
.then((response) => {
return response.json()
})
.then((resData: IpriceDataArray) => {
resolve(resData)
})
})
}
getPriceData().then((res) => {
console.log(res)
})
//后端多用的类型 nodejs BFF框架模式
interface ClockConstructor {
new (hour: number, minute: number): ClockInterface
}
interface ClockInterface {
tick(): void
}
class DigitalClock implements ClockInterface {
public tick(): void {
console.log('beep bepp')
}
}
class AnalogClock implements ClockInterface {
public tick(): void {
console.log('duang duang')
}
}
function createClock(
ctor: ClockConstructor,
hour: number,
minute: number
): ClockInterface {
return new ctor(hour, minute)
}
const digtal = createClock(DigitalClock, 12, 127)
const digta2 = createClock(AnalogClock, 7, 127)
digtal.tick()
digta2.tick()