ทำให้คุณสมบัติเป็นตัวเลือกในคลาสย่อยของ TypeScript
ฉันพึ่งเริ่มใช้ Typescript ฉันกำลังใช้ Typescript 4.4 และฉันรู้จัก Utility types (Pick, Omit, Partial, ...) แต่สิ่งเหล่านี้ใช้ได้เฉพาะกับ types และ interfaces เท่านั้น ไม่สามารถใช้กับ classes ได้ ฉันไม่สามารถใช้ interfaces ได้เพราะฉันกำลังใช้ TypeGraphQL และ framework นั้นต้องการ classes แทน interfaces
เพื่อที่จะลดการทำซ้ำของโค้ด ผมกำลังพยายามทำสิ่งต่อไปนี้:
class User {
id!: string;
firstName!: string;
lastName!: string;
email!: string;
street?:string;
... many more fields
}
class UserForUpdate extends Partial<User> {} //fails with 'Partial' only refers to a type, but is being used as a value here
หรือ
class UserForUpdate extends User {
id?: string; //fails with Type 'string | undefined' is not assignable to type 'string'.
firstName?: string; //fails with Type 'string | undefined' is not assignable to type 'string'.
lastName?: string; //fails with Type 'string | undefined' is not assignable to type 'string'.
email?: string; //fails with Type 'string | undefined' is not assignable to type 'string'.
}
ฉันก็ได้ลองสิ่งต่อไปนี้ด้วย:
function forUpdating<T extends { new (...args: any[]) : any, prototype: any }>(ctor: T): Partial<T> & { new (...args: any[]): T } {
return ctor as any;
}
export class TestUser extends forUpdating(User) {
// fails with The types of 'prototype.id' are incompatible between these types.
// Type 'string | undefined' is not assignable to type 'string'.
// Type 'undefined' is not assignable to type 'string'.
id?: string;
firstName?: string;
lastName?: string;
email?: string;
}
มีวิธีง่าย ๆ ที่จะทำให้คุณสมบัติทั้งหมดที่จำเป็น ของคลาส เป็นตัวเลือกได้ไหม?
คำตอบ #1
ถ้าคลาสของคุณมีเพียงฟิลด์เท่านั้น โดยทั่วไปฉันจะไม่แนะนำให้สร้างคลาสจริง ๆ คุณจะได้ผลดีกว่าหากใช้อินเทอร์เฟซ
class User {
id!: string;
firstName!: string;
lastName!: string;
email!: string;
street?:string;
}
interface UserForUpdate extends Partial<User> {}
const user: UserForUpdate = {
id: "",
}
ลิงก์สนามเด็กเล่น
ถ้าคุณต้องการนำฟิลด์จากอินเทอร์เฟซไปยังคลาส คุณสามารถใช้การรวมอินเทอร์เฟซกับคลาสได้:
class User {
id!: string;
firstName!: string;
lastName!: string;
email!: string;
street?:string;
}
interface UserForUpdate extends Partial<User> {}
class UserForUpdate {
}
const user: UserForUpdate = new UserForUpdate()
user.email = ""
ลิงก์สนามเด็กเล่น
