function isString(test: any): test is string {
return typeof test === 'string'
}
function isString(test: any): boolean {
return typeof test === 'string'
}
function isString(test: any): test is string {
return typeof test === 'string'
}
function example(foo: any) {
if (isString(foo)) {
console.log('it is a string' + foo)
console.log(foo.length) // string function
// 如下代码编译时会出错,运行时也会出错,因为 foo 是 string 不存在 toExponential 方法
console.log(foo.toExponential(2))
}
// 编译不会出错,但是运行时出错
console.log(foo.toExponential(2))
}
example('hello world')
function isString(test: any): boolean {
return typeof test === 'string'
}
function example(foo: any) {
if (isString(foo)) {
console.log('it is a string' + foo)
console.log(foo.length) // string function
// foo 为 any,编译正常。但是运行时会出错,因为 foo 是 string 不存在 toExponential 方法
console.log(foo.toExponential(2))
}
}
example('hello world')
function isAxiosError(error: any): error is AxiosError {
return error.isAxiosError
}
if (isAxiosError(err)) {
code = `Axios-${err.code}`
}
type ParamType<T> = T extends (param: infer P) => any ? P : T
type FunctionType = (value: number) => boolean
type Param = ParamType<FunctionType> // type Param = number
type OtherParam = ParamType<symbol> // type Param = symbol
type ReturnValueType<T> = T extends (param: any) => infer U ? U : T
type FunctionType = (value: number) => boolean
type Return = ReturnValueType<FunctionType> // type Return = boolean
type OtherReturn = ReturnValueType<number> // type OtherReturn = number
function print(value: number | string) {
// 如果是 string 类型
// console.log(value.split('').join(', '))
// 如果是 number 类型
// console.log(value.toFixed(2))
}
function print(value: number | string) {
if (typeof value === 'string') {
console.log(value.split('').join(', '))
} else {
console.log(value.toFixed(2))
}
}
class Bird {
fly() {
console.log('Bird flying')
}
layEggs() {
console.log('Bird layEggs')
}
}
class Fish {
swim() {
console.log('Fish swimming')
}
layEggs() {
console.log('Fish layEggs')
}
}
const bird = new Bird()
const fish = new Fish()
function start(pet: Bird | Fish) {
// 调用 layEggs 没问题,因为 Bird 或者 Fish 都有 layEggs 方法
pet.layEggs()
if (pet instanceof Bird) {
pet.fly()
} else {
pet.swim()
}
// 等同于下面
// if ((pet as Bird).fly) {
// (pet as Bird).fly();
// } else if ((pet as Fish).swim) {
// (pet as Fish).swim();
// }
}
interface Point {
x: number
y: number
}
// type keys = "x" | "y"
type keys = keyof Point
function get(o: object, name: string) {
return o[name]
}
function get<T extends object, K extends keyof T>(o: T, name: K): T[K] {
return o[name]
}
class Animal {
type: string
weight: number
private speed: number
}
type AnimalProps = keyof Animal // 'type' | 'weight'