示例工程 12-variance-soundness
12-variance-soundness/03-method-bivariance/src/main.ts
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// 演示:方法参数是双变的(bivariant),比函数属性更宽松
export type Animal = { name: string };
export type Dog = Animal & { bark(): void };
export interface MethodBox {
set(value: Animal): void;
}
export interface FunctionBox {
set: (value: Animal) => void;
}
// 方法声明允许更窄的参数
export const methodBox: MethodBox = {
set(value: Dog) {
if ('bark' in value) {
value.bark();
}
},
};
export function run(log: (msg: string) => void = console.log): string[] {
methodBox.set({ name: 'Rex' });
const lines = ['method:ok'];
for (const line of lines) {
log(line);
}
return lines;
}