传播运算符不是类型安全的

par*_*yzm 1 spread typescript

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

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, :(

    // This is too verbose... but works
    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
Run Code Online (Sandbox Code Playgroud)

有没有办法使其类型安全,同时将样板文件保持在最低限度?

游乐场代码在这里

Kou*_*sha 5

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

interface State {
    fieldA: number;
    fieldB: string;
}
interface Tmp {
    fieldA: string;
    fieldB: string;
    payload: string;
}
Run Code Online (Sandbox Code Playgroud)

换句话说,扩展运算符执行以下操作:

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;
}
Run Code Online (Sandbox Code Playgroud)

展开运算符正在为您创建一种新类型的对象;如果你想推断类型,那么你应该这样做:

// this now throws an error
const tmp: State = { ...state, feildB: action.payload };
Run Code Online (Sandbox Code Playgroud)