Reputation: 1499
I have a function that is supposed to return some type but using the spread operator caused it to assign a misspelled key.
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
Is there a way to make it typesafe, while keeping the boilerplate to the minimum?
Upvotes: 4
Views: 2108
Reputation: 36299
TypeScript is doing what it is supposed to do. In your case, you are creating a new object tmp
with a new type that has 3 fields, namely:
interface State {
fieldA: number;
fieldB: string;
}
interface Tmp {
fieldA: string;
fieldB: string;
payload: string;
}
In other words, the spread operator performs the following operation:
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;
}
The spread operator is creating a new type of object for you; if you want to infer the type, then you should do:
// this now throws an error
const tmp: State = { ...state, feildB: action.payload };
Upvotes: 5