interface 中定义函数的三种方法
interface Person {
readonly name: string,
say?: {(a: string): string},
run?(a: string): boolean,
eat?: (a: string) => string,
}
断言、双重断言
有相同属性的可以断言
interface Person {
name: string,
}
interface Dog {
nickname: string,
age: number,
}
interface Cat {
nickname: string,
}
const c1: Cat = {
nickname: 'cc1',
}
console.log(c1 as Dog) // 这个没有问题
console.log(c1 as Person) // 这个会报错
// 类型 "Cat" 到类型 "Person" 的转换可能是错误的,因为两种类型不能充分重叠。
// 如果这是有意的,请先将表达式转换为 "unknown"
// 下面是可以的
console.log(c1 as unknown)
console.log(c1 as any)
console.log(c1 as unknown as Person)
console.log(c1 as any as Person)
泛型&泛型约束
interface CreateSomeOne<T> {
(a: T): T,
}
interface Lengthwise {
age: number;
}
function createSomeOne<T extends Lengthwise>(a: T, b: T): T {
if (a.age > 0) return a;
else return b;
}