【发布时间】:2019-01-04 23:09:50
【问题描述】:
我正在使用 TypeScript 编写我的应用程序,并且我正在使用 Redux 来跟踪我的应用程序状态。我的 redux 存储状态如下所示:
interface AppState {
readonly grid : IGridSettings;
readonly selected : ISelectedSettings;
[key : string] : IGridSettings | ISelectedSettings;
}
interface IGridSettings {
readonly extents : number;
readonly isXY : boolean;
readonly isXZ : boolean;
readonly isYZ : boolean;
readonly spacing : number;
[key : string] : number | boolean;
}
interface ISelectedSettings {
readonly bodyColor : number;
readonly colorGlow : number;
readonly lineColor : number;
readonly selection : number[] | undefined;
[key : string] : number | number[] | undefined;
}
我创建了以下操作来更新商店,但是 setPropertyValue 函数并不理想,因为它没有类型安全性!
//How to add type safety to this function?
const setPropertyValue = ( property : string[], value : any ) : SetPropertyValueAction => ( {
type: 'SET_PROPERTY_VALUE',
payload: {
property,
value,
}
} );
interface SetPropertyValueAction extends Action {
type : string;
payload : {
property : string[];
value : any;
};
}
我可以通过这种方式在我的代码中使用此操作:
setPropertyValue( ['grid', 'extents'], 100 );
这可行,但由于 setPropertyValue 函数中没有类型安全,因此没有什么限制我将无效值输入到函数中,如下所示:
setPropertyValue( ['grid', 'size'], 100 ); //invalid since IGridSettings doesn't have a 'size' property
setPropertyValue( ['grid', 'isXY'], -1 ); //value should be a boolean not a number
setPropertyValue( ['selected', 'bodyColor'], '255' ); //value should be a number not a string
有没有办法重写 setPropertyValue 函数,使其只接受对 AppState 中的属性名称有效的参数。此外,传入的值必须与所选属性的正确类型相对应。
也许使用字符串数组来更改 property 并不理想,但我不知道有更好的方法来仅针对 AppState 中可用的属性。
【问题讨论】:
-
您的用例是否需要索引签名,或者您是否只是添加它们以允许索引? (例如:
[key : string] : IGridSettings | ISelectedSettings;) -
我需要添加索引签名以消除沿途某处的错误消息。没有它们,TypeScript 代码将无法为我编译。
标签: typescript redux type-safety