phone
존재 여부를 확인할 때 작동하지 않는 이유 . TypeScript는이를 포착하고 phone
존재 하는지 알고 있어야하며 AddressWithPhone
인터페이스 여야합니다 .
너무 길어서 유형을 올바르게 정의하지 않았을 것입니다.
interface Address {
street: string;
zip: string;
state: string;
city: string;
}
interface AddressWithPhone extends Address {
phone: string;
}
interface EditAddressProps<T = Address | AddressWithPhone> {
address: T;
onChange: (address: T) => unknown;
}
const something = <T,>(props: EditAddressProps<T>): string => {
// Error: Property 'phone' does not exist on type 'T'
if (props.address.phone) {
return 'Its AddressWithPhone';
}
return 'Its Address without phone';
}
TS 운동장 :
당신이 <T = Address | AddressWithPhone>
할 때 당신은 T
조합 의 기본값을 설정하고 Address | AddressWithPhone
있습니다. 실제로 가능한 값을 제한하지 않았 T
으므로 T
여전히 아무것도 될 수 있습니다.
extends
의 가능한 값을 제한하는 데 사용하려고합니다 T
. 에 phone
정의되지 않았기 때문에 여전히 공용체에서 완벽하게 작동하지 않으며 Address
속성에 액세스하려면 공용체의 모든 멤버에서 속성을 정의해야합니다. Address
필수 및 phone
선택 속성의 모든 속성이있는 기본 유형이 필요합니다 . 이를 정의하는 방법에는 여러 가지가 있지만 여기에 하나가 있습니다.
type BaseAddress = Address & Partial<AddressWithPhone>
const something = <T extends BaseAddress>(props: EditAddressProps<T>): string => {
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다