【发布时间】:2020-10-16 20:37:19
【问题描述】:
我在类似函数的 reducer 中遇到了一些类型错误(我的目标是能够使用我的 state 中的 formData 生成表单)。
但由于减速器函数中的此错误,我正在努力输入表单属性:
Index signatures are incompatible.
Types of property 'initialValues' are incompatible.
Type 'string' is not assignable to type 'number'.ts(2322)
代码:
type Attribute = StringAttribute | DecimalAttribute;
enum Type {
DECIMAL = 'decimal',
STRING = 'string',
}
interface StringAttribute {
isErrored: boolean;
isMissingData: boolean;
initialValues: string;
values: string;
attributeDefinition: {
type: Type.STRING;
helperText: string;
label: string;
}
}
const isStringAttribute = (attribute: Attribute): attribute is StringAttribute => attribute.attributeDefinition.type === Type.STRING;
interface DecimalAttribute {
isErrored: boolean;
isMissingData: boolean;
initialValues: number;
values: number;
attributeDefinition: {
type: Type.DECIMAL;
helperText: string;
label: string;
}
}
const isDecimalAttribute = (attribute: Attribute): attribute is DecimalAttribute => attribute.attributeDefinition.type === Type.DECIMAL;
type Action =
| { type: 'updateStringValue', attributeIdentifier: string; value: string }
| { type: 'updateDecimalValue', attributeIdentifier: string; value: number }
interface State {
formData: Record<string, Attribute>
}
const reducer = (state: State, action: Action): State => {
switch (action.type) {
case 'updateDecimalValue': {
const attribute = state.formData[action.attributeIdentifier];
if (isDecimalAttribute(attribute)) {
return {
...state,
formData: {
...state.formData,
[action.attributeIdentifier]: {
...state.formData[action.attributeIdentifier],
values: action.value
}
}
}
}
return state;
}
}
}
const initialState: State = {
formData: {
stringAttributeIdentifier: {
isErrored: false,
isMissingData: false,
values: 'String data',
initialValues: 'String data',
attributeDefinition: {
type: Type.STRING,
helperText: 'Some Helper Text',
label: 'My Attribute Label'
}
},
decimalAttributeIdentifier: {
isErrored: false,
isMissingData: false,
values: 13.32,
initialValues: 13.32,
attributeDefinition: {
type: Type.DECIMAL,
helperText: 'Some Helper Text',
label: 'My Attribute Label'
}
},
}
}
【问题讨论】:
标签: typescript typescript-typings