아래 예제가 실제로 오류를 가질 수 없다는 것을 알아낼만큼 Typescript가 똑똑하지 않은 이유는 무엇입니까?
interface M1 {
props: {
color: 'red' | 'blue';
transparency: 0 | 1;
},
f: (props: M1['props']) => string
}
interface M2 {
props: {
age: number;
country: string;
},
f: (props: M2['props']) => string
}
const myFunc = (param: M1 | M2) => {
return param.f(param.props)
}
myFunc
의 매개 변수는 M1 또는 M2이지만 둘다는 아닙니다. 그래서 그것이 무엇이든 param.f(params.props)
, 당신이을 호출 할 때 , 당신은 그것이 params.props
의 입력과 같은 유형 임을 알 수 param.f
있습니다.
이 논리가 잘못되었거나 TS가이를 추론 할 수없는 이유는 무엇입니까?
이러한 제한을 해결하는 한 가지 방법은 수퍼 인터페이스를 만들고 다형성 유형M
을 M
사용하는 방법을 정의하는 것입니다 .this
interface M {
props: { [name: string]: any };
f: (props: this['props']) => string;
}
interface M1 extends M {
props: {
color: 'red' | 'blue';
transparency: 0 | 1;
}
}
interface M2 extends M {
props: {
age: number;
country: string;
}
}
const myFunc = (param: M) => {
return param.f(param.props);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다