객체의 메서드를 타이핑할 때도 타이핑 방법에 따라 변성이 정해집니다. strict 옵션이 활성화된 상황입니다.
interface SayMethod {
say(a: string | number): string;
}
interface SayFunction {
say: (a: string | number) => string;
}
interface SayCall {
say: {
(a: string | number): string
}
}
const sayFunc = (a: string) => 'hello';
const MyAddingMethod: SayMethod = {
say: sayFunc //이변성
}
const MyAddingFunction: SayFunction = {
say: sayFunc //반공변성
}
const MyAddingCall: SayCall = {
say: sayFunc //반공변성
}
// Type '(a: string) => string' is not assignable to type '(a: string | number) => string'. Types of parameters 'a' and 'a' are incompatible. Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.