TypeScript类型不适用于传播算子 [英] TypeScript type not working with spread operator

查看:87
本文介绍了TypeScript类型不适用于传播算子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个redux风格的reducer(我正在使用ngrx),它返回一个特定的类型.当我在返回对象中使用spread运算符时,打字稿短绒没有捕获无效的属性.

I have a redux style reducer (I'm using ngrx) that is returning a specific type. When I use the spread operator in my return object, the typescript linter is not catching invalid properties.

这是我的界面:

interface MyState {
    firstName: string;
    lastName: string;
    age: number;
}

这是我的减速器. Action是ngrx动作:

Here is my reducer. Action is an ngrx action:

function reducer(state = initialState, action: Action): MyState {
    switch (action.type) {
        case Actions.COOL_ACTION:
            return {
                ...state,
                propertyDoesNotExist: action.payload, // <- no error
            };
        default:
            return state;
    }
}

我希望propertyDoesNotExist会被标记,但是不会.我试过强制转换<CalendarState>返回对象,状态属性...(<CalendarState>state)并使用as别名,但这无济于事.

I would expect that propertyDoesNotExist would be flagged, but it is not. I've tried casting <CalendarState> the return object, the state property ...(<CalendarState>state) and using the as alias, but it doesn't help.

这就像传播运算符弄乱了类型.

It's like the spread operator messes up the types.

推荐答案

通过使用...state,返回的表达式不再是对象文字,并且TypeScript不会抱怨它是否是返回类型的子类型(即具有额外的属性).我自己遇到了这个问题,并编写了一个小的辅助函数来表示其他属性:

By using ...state, the returned expression is no longer an object literal, and TypeScript won't complain if it's a subtype of the return type (i.e. has extra properties). I ran into this problem myself and wrote a little helper function to signal extra properties:

const applyChanges = <S, K extends keyof S>(state : S, changes : Pick<S, K>) : S =>
  Object.assign({}, state, changes);

(由于此问题,使用Object.assign而不是传播运算符: https://github .com/Microsoft/TypeScript/issues/14409 )

(using Object.assign instead of spread operators because of this issue: https://github.com/Microsoft/TypeScript/issues/14409)

要使用applyChanges,只需替换

return {...state,
    propertyDoesNotExist: action.payload, // <- no error
};

使用

return applyChanges(state, {
    propertyDoesNotExist: action.payload, // <- error
});

这篇关于TypeScript类型不适用于传播算子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆