เอกสารสำหรับ ประเภททูเพิลที่แมป เสนอตัวอย่างนี้:
type MapToPromise<T> = { [K in keyof T]: Promise<T[K]> };
type Coordinate = [number, number]
type PromiseCoordinate = MapToPromise<Coordinate>; // [Promise<number>, Promise<number>]
แต่จะเกิดอะไรขึ้นถ้าทูเปิลดั้งเดิมของฉันมีสิ่งอันดับอื่นๆ และในฐานะส่วนหนึ่งของการแมป ฉันต้องการดึงค่าที่น่าสนใจออกจากทูเปิลภายในเหล่านั้น
e.g.
// I just want the numbers, but there is other stuff in the type
type MessyCoordinate = [
[string, number],
[string, number]
]
ฉันคาดหวังว่าฉันจะทำสิ่งนี้ได้:
type Clean<T extends [string, number]> = T[1]
// Why doesn't this work?
type MapToClean<T> = { [K in keyof T]: Clean<T[K]> }
type CleanCoordinate = MapToClean<MessyCoordinate>; // [number, number]
คอมไพเลอร์ให้ข้อผิดพลาดนี้แก่ฉัน:
Type 'T[K]' does not satisfy the constraint '[string, number]'.
Type 'T[keyof T]' is not assignable to type '[string, number]'.
Type 'T[string] | T[number] | T[symbol]' is not assignable to type '[string, number]'.
Type 'T[string]' is not assignable to type '[string, number]'.(2344)
ฉันสามารถลองเพิ่มข้อจำกัดเพิ่มเติมใน MapToClean
ได้ แต่ดูเหมือนจะไม่ช่วยอะไร:
type MapToClean2<T extends [string, number][]> = { [K in keyof T]: Clean<T[K]> }
ฉันยังสามารถกำจัดประเภทยูทิลิตี้ Clean
ได้ด้วยและทำสิ่งนี้ แต่มันก็ไม่ได้ผลเช่นกัน:
// Why doesn't this work?
type MapToClean<T> = { [K in keyof T]: T[K][1] }
// Type '1' cannot be used to index type 'T[K]'.
type CleanCoordinate = MapToClean<MessyCoordinate>; // [number, number]
ความคาดหวังพื้นฐานของฉันที่ฉันควรจะสามารถเปิดทูเพิลในการแมปนั้นมีข้อบกพร่องหรือไม่ หรือฉันแค่ขาดไวยากรณ์เล็กน้อยเพื่อให้ T[K]
ดูเหมือน [string, number]