ค้นหาเว็บไซต์

reactjs - React/Typescript 2 คุณสมบัติทางเลือกที่ต้องใช้ร่วมกัน


แนวทางปฏิบัติที่ดีที่สุดในการมี props แบบเลือกได้ 2 ตัวในคอมโพเนนต์ที่จำเป็นต้องใช้ร่วมกันกับ React/TypeScript คืออะไร

export interface MyComponentProps {
  firstName?: string;
  lastName?: string;
}
const myComponent: React.FC<MyComponentProps> = (props) => { 
       return <div ...>
     }

ความคิดของฉันเกี่ยวกับความจำเป็นทั้งสองอย่าง

export interface Name {
    firstName: string;
    lastName: string;
}
export interface MyComponentProps {
     name?: Name
}

นี่จะเป็นวิธีที่ดีที่สุดหรือมีวิธีแก้อื่นอยู่หรือไม่?

คำตอบ #1

คุณสามารถใช้ชนิดทั่วไปนี้ ซึ่งรับชนิดหนึ่งและทำให้แน่ใจได้ว่าทั้งหมดสามารถมีอยู่ได้หรือไม่มีเลย

type AllOrNone<T> = Required<T> | Partial<Record<keyof T, undefined>>;

ในกรณีของคุณ การใช้งานจะเป็น

export interface Name {
    firstName: string;
    lastName: string;
}

export type MyComponentProps = AllOrNone<Name>;

คุณสามารถลองใช้มันใน TS Playground ได้

บทความที่เกี่ยวข้อง