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

typescript - ข้อจำกัด extends ที่มีเครื่องหมายเท่ากับในนิยามประเภททั่วไปมีผลอย่างไร?


ฉันเคยเห็นไวยากรณ์ extends นี้:

export type MyType<Data extends Base = Base> = { data: Data }

การใช้งาน Base=Base ทำอะไรได้บ้าง?

เอกสาร TypeScript เกี่ยวกับเจเนอริกไม่ได้อธิบายมัน

คำตอบ #1

พารามิเตอร์ทั่วไปเริ่มต้น - เอกสาร

มันอนุญาตให้คุณเรียก MyType โดยไม่ต้องมีพารามิเตอร์เจนเนอริก

type Base = { tag: 'Base' }

export type MyType<Data extends Base = Base> = { data: Data }

// type WithArgument = {
//     data: {
//         tag: 'Base';
//         name: 'John';
//     };
// }
type WithArgument = MyType<{ tag: 'Base', name: 'John' }>

// { data: Base; }
type Result = MyType 

การเปรียบเทียบแบบจาวาสคริปต์บริสุทธิ์:

const myType = (arg = { tag: 'Base' }) => arg
const result = myType() // { tag: 'Base' }

นี่คือ Data extends Base=Base หมายความว่า:

  1. Data ควรขยายจาก Base
  2. หากไม่ได้ให้ข้อมูล ใช้ค่า Base เป็นค่าเริ่มต้น

นี่คือวิธีที่มันสามารถแบ่งออกเป็นสองส่วนได้:

  1. Data extends Base
  2. Data = Base

คุณไม่ควรอ่าน Base=Base แยกจาก extends word

คำตอบ #2

นี่คือค่าตั้งต้นของชนิดทั่วไป ตัวอย่างเช่น:

type MyType<Data extends Object = String> = { data: Data }

let test: MyType = {data: 'test'}; // Same as MyType<string>

console.log(typeof test.data); // prints string

let test2: MyType<Number> = {data: 5}; 

console.log(typeof test2.data); // prints number