1
배열에서 A와 B 중 하나가 2 가지 유형 중 하나를 시행하도록합니다. B는 A를 확장합니다. 어떻게 수행합니까?2 인터페이스의 Typescript 통합은 모호한 코드를 허용합니다
interface Foo {
x: string;
}
interface Bar extends Foo {
y: string;
z: number;
}
type X = Foo | Bar;
const arr: Array<X> = [
{ x: 'Hello' }, // implements Foo
{ x: 'John', y: 'Doe', z: 42 }, // implements Bar
{ x: 'Hello', y: 'World' }, // i want this to throw an error
];
감사합니다 :)
만약'const jane : Foo = {x : 'Doe', y : 4}'라고 쓰면 오류가 발생합니다. 마찬가지로 배열이'const arr : Array'이면 arr [1]과 arr [2]가 던져 버린다. 'y를 추가해야합니까? : string'과'z? : string'을'Foo'의 선언에 추가합니다. 고마워 :) –
그래, 조금 무작위이지만 컴파일러는 할당과 같은 몇 가지 장소에서 정확한 유형을 확인합니다. – AlexG