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

การอนุมานประเภทสูญเสียประเภทระดับภายในใน TypeScript


ในตัวอย่างโค้ดด้านล่าง ฉันไม่สามารถหาสาเหตุได้ว่า FinalType เป็น { test: { test_inner: any } } ได้อย่างไร ฉันไม่รู้ว่า any มาจากไหน (และ string หายไป) ขณะเดียวกัน test มีประเภทการคืนค่าที่ถูกต้องเป็น { test_inner: string }

interface IAction {
    type: string;
}

type Reducer<S> = (state: S, action: IAction) => S

function combineReducers<S>(reducers: { [K in keyof S]: Reducer<S[K]> }): Reducer<S> {
    const dummy = {} as S;
    return () => dummy;
}

const test_inner = (test: string, action: IAction) => {
    return 'dummy';
}
const test = combineReducers({
    test_inner
});

const test_outer = combineReducers({
    test
});

type FinalType = ReturnType<typeof test_outer>;

ฉันกำลังอยู่ในขั้นตอนการพิมพ์แอปพลิเคชัน redux ของฉัน แต่ฉันคิดว่าปัญหาไม่น่าจะเฉพาะเจาะจงกับ redux ฉันทราบดีเกี่ยวกับ @types/redux แต่ฉันไม่อยากใช้มัน

คำตอบ #1

นี่คือบั๊กในการที่ TypeScript แสดงประเภทกลับให้คุณเห็น - บันทึกไว้ที่ https://github.com/Microsoft/TypeScript/issues/23897

ประเภท จริง ของ FinalType เป็นจริงตามที่ถูกต้อง; มันเป็นเพียงข้อบกพร่องในการแสดงผลเท่านั้น.