分散运算符类型不安全

时间:2019-12-01 20:37:13

标签: typescript spread

我有一个应该返回某种类型的函数,但是使用散布运算符导致它分配了拼写错误的键。

interface State {
    fieldA: number,
    fieldB: string
}

const reducer: (state: State, action: {payload: string}) => State = (state, action) => {

    // please note that those variables are not desired
    const tmp = { ...state, feildB: action.payload }; // No compile time error, as I would expect

    // This is too verbose... but works as expected
    const tmp2 = Object.assign<State, Partial<State>>(state, {feildB: action.payload}) // ERROR - this is what I need
    return tmp
}
const t = reducer({fieldA: 1, fieldB: 'OK'}, {payload: 'Misspelled'}) // Misspelled
console.log("feildB", (t as any).feildB) // Misspelled
console.log("fieldB", (t as any).fieldB) // OK

有没有办法使它的类型安全,同时将样板保持在最小?

Playground code HERE

1 个答案:

答案 0 :(得分:6)

TypeScript正在执行应做的事情。在您的情况下,您正在创建一个新对象tmp,其新类型具有3个字段,即:

interface State {
    fieldA: number,
    fieldB: string
}
interface Tmp {
    fieldA: string;
    fieldB: string;
    feildB: string;
}

换句话说,价差运算符执行以下操作:

interface Obj {
    [key: string]: any;
}

const spread = (...objects: Obj[]) => {
    const merged: Obj = {};

    objects.forEach(obj => {
        Object.keys(obj).forEach(k => merged[k] = obj[k]);
    });

    return merged;
}

spread运算符正在为您创建一种新型的对象;如果要推断类型,则应该执行以下操作:

// this now throws an error
const tmp: State = { ...state, feildB: action.payload };