any可以是任何类型
下列代码即使我们期望返回值是string,但是仍然可以返回任何类型的值
function selectDeliverAddress(addressOrIndex: any):string {
if(typeof addressOrIndex === 'number' && addressOrIndex < deliveryAddresses.length) {
return deliverAddresses[addressOrIndex]
}
return addressOrIndex
}
const myFavouriteAddress = selectDeliverAddress(true)
如果我们使用unknown类型,我们必须做类型检查,否则会报错
function selectDeliverAddress(addressOrIndex: any):string {
if(typeof addressOrIndex === 'number' && addressOrIndex < deliveryAddresses.length) {
return deliverAddresses[addressOrIndex]
} else if(typeof addressOrIndex === 'string'){
return addressOrIndex
}
return ''
}
const myFavouriteAddress = selectDeliverAddress(true)
P.S.
Subtypes and Supertypes
For example, any is the supertype of all types, and string is
a subtype of any.