javascript 前端 Typescript——基础篇(2) - string'
一、Typescript——泛型:generics
1、泛型出现的动机
function easyFunction (someone: number) {
return someone
}
const test = easyFunction(123) // 鼠标放在test上显示:const test: any
此处通过例子可发现,test丧失了类型,这是不好的现象,解决方法:可以通过赋一个默认类型:
function easyFunction (someone: number): number {
return someone
}
const test = easyFunction(123) // 鼠标放在test,显示:const test: number
但是,我们传入的变量,有可能是boolean、string、复杂类型等。此时,我们可以用泛型解决
2、泛型是什么
泛型是指在定义函数、接口或者类的时候,我们不预先指定具体的类型,类似于一种占位符,然后在使用的时候再动态的填入指定的类型
function easyFunction(someone: S): S {
return someone
}
const result = easyFunction('123') // const result: "123"
const result1 = easyFunction(123) // const result1: 123
const result2 = easyFunction(true) // const result2: true
泛型之多种属性
function easyFunction(someone: [S, N]): [N, S] {
return [someone[1], someone[0]]
}
const result = easyFunction(['123', 123]) // const result3: [number, string]
result[0].toString()
result[1].length
3、约束泛型
3-1、约束泛型概念的由来
function easyFunction(someone: S):S {
console.log(someone.length) // 会报错
return someome
}
我们在使用泛型的时候,由于事先不知道是属于哪种类型,因此我们不能随意的操纵它的属性或方法。
解决:当我们确定了此函数是作用于含有S类型的Array时,就可以让someone的类型不是简单的S,而是含有S的Array
function easyFunction(someone: S[]): S[] {
console.log(someone.length)
return someone
} 拼多多帮助力入口
const result = easyFunction([1, '2', true]) // const array: (string | number | boolean)[]
const errorMsg = easyFunction('123') // 报错
我们发现,明明string和array都有length属性,但是传入string 就会报错。因为此时 string 类型的 123 无法赋值给 array 类型,因此我们需要新的解决方案,给泛型一个约束,只允许函数传入那些包含length属性的变量,这就是约束泛型
3-2、约束泛型——extends
interface IWithLength {
length: number
}
function echoWidthLength(someone:S):S {
console.log(someone.length)
return someone
}
const string = echoWidthLength('string')
// obj 中需要含有length,才能让 someone.length 不报错
const obj = echoWidthLength({length: 10, width: 20})
const array = echoWidthLength([1, 2, 3])
// 总结:只要你有length属性,那就可以符合这个约束,就没问题,不管是什么类型都可以
精彩链接,javascript