redux - อินเทอร์เฟซ TypeScript พร้อมสมาชิกแบบกระจาย
ฉันกำลังนำเข้าจำนวนมากของทรัพย์สินทีละหลายรายการด้วย
import * as actionCreators from './billingUtil2';และ TypeScript กำลังระบุการส่งออกแต่ละรายการภายใน actionCreators อย่างถูกต้อง สามารถ "กระจาย" สมาชิกเหล่านั้นเข้าไปในอินเทอร์เฟซได้หรือไม่? โดยอุดมคติคือบางสิ่งแบบนี้ แต่ต้องถูกต้อง
interface componentState {
...actionCreators
}
กรณีการใช้งานของฉันคือ ฉันต้องการสร้างคอมโพเนนต์ React และอธิบายรูปร่างของ props ที่มันจะได้รับจาก Redux อย่างแม่นยำ ดังนั้นในอุดมคติควรเป็นอะไรประมาณนี้
import * as actionCreators from './billingUtil2';
interface State {
name: string;
age: number
}
interface componentState extends State {
...actionCreators
}
แล้วจากนั้นฉันก็สามารถบอก TypeScript ให้คาดหวัง props ในรูปแบบ componentState ได้ ตัว reducer ของ redux ของฉันก็จะส่งผลลัพธ์ที่ทำตาม interface อยู่แล้ว เป้าหมายหลักของฉันที่นี่คือการหลีกเลี่ยงการพิมพ์ action creator แต่ละตัวด้วยมือ
คำตอบ #1
คุณสามารถสร้างประเภทการตัดกันได้
import * as actionCreators from './billingUtil2';
type MyState = typeof actionCreators & {
name: string
age: number
}
หรือจากโค้ดของคุณในส่วนที่สองด้านบน ซึ่งคุณมีอินเทอร์เฟซ State คุณสามารถทำได้
import * as actionCreators from './billingUtil2';
interface State {
name: string;
age: number
}
type componentShape = typeof actionCreators & State;
หรือคุณก็สามารถทำเช่นเดียวกันได้
type acT = typeof actionCreators
interface MyState extends acT {
name; age;
}
class Comp extends React.Component<{}, MyState> {
}
