สำหรับการกวดขันประเภทของทรัพย์สินที่ง่ายextendทำงานที่สมบูรณ์แบบเช่นเดียวกับในคำตอบของ Nitzan :
interface A {
x: string | number;
}
interface B extends A {
x: number;
}
สำหรับการขยับขยายหรือโดยทั่วไปการแทนที่ประเภทคุณสามารถทำวิธีแก้ปัญหาของ Zskycat :
interface A {
x: string
}
export type B = Omit<A, 'x'> & { x: number };
แต่หากอินเทอร์เฟซของคุณAขยายส่วนติดต่อทั่วไปคุณจะสูญเสียAคุณสมบัติที่เหลืออยู่ของประเภทที่กำหนดเองเมื่อใช้Omitคุณสมบัติส่วนที่เหลือเมื่อใช้
เช่น
interface A extends Record<string | number, number | string | boolean> {
x: string;
y: boolean;
}
export type B = Omit<A, 'x'> & { x: number };
let b: B = { x: 2, y: "hi" };
เหตุผลก็คือOmitภายในจะไปที่Exclude<keyof A, 'x'>กุญแจเท่านั้นซึ่งจะเป็นเรื่องทั่วไปstring | numberในกรณีของเรา ดังนั้นBจะกลายเป็น{x: number; }และยอมรับคุณสมบัติพิเศษใด ๆ ที่มีประเภทของnumber | string | boolean.
เพื่อแก้ไขปัญหานี้ฉันได้สร้างOverridePropsยูทิลิตี้ประเภทอื่นดังต่อไปนี้:
type OverrideProps<M, N> = { [P in keyof M]: P extends keyof N ? N[P] : M[P] };
ตัวอย่าง:
type OverrideProps<M, N> = { [P in keyof M]: P extends keyof N ? N[P] : M[P] };
interface A extends Record<string | number, number | string | boolean> {
x: string;
y: boolean;
}
export type B = OverrideProps<A, { x: number }>;
let b: B = { x: 2, y: "hi" };