当不可变记录中存在枚举时,打字稿会出错
Typescript errors out when enums are present inside an Immutable record
import { Record } from 'immutable'
export enum PriceRelationType {
nForX,
nForPriceOfX
}
export interface PriceRelation {
type: PriceRelationType
quantity: number
price: number
}
export interface ProductType {
id: string
name: string
image: string
description: string
price: {
relations: PriceRelation[]
scale: number
}
}
export const ProductRecord: Record.Factory<ProductType> = Record({
id: '',
name: '',
image: '',
description: '',
price: {
relations: [{ quantity: 0, price: 0, type: PriceRelationType.nForX }],
scale: 0
}
})
对于给定的代码块,Typescript 通过给出以下错误拒绝编译它
Types of property 'price' are incompatible.
Type '{ relations: PriceRelation[]; scale: number; } | undefined' is not assignable to type '{ relations: { quantity: number; price: number; type: PriceRelationType.nForX; }[]; scale: number; } | undefined'.
Type '{ relations: PriceRelation[]; scale: number; }' is not assignable to type '{ relations: { quantity: number; price: number; type: PriceRelationType.nForX; }[]; scale: number; }'.
枚举值似乎有问题,删除它可以修复错误。
我怀疑显式输入关系数组可以解决这个问题,例如:
export const ProductRecord: Record.Factory<ProductType> = Record({
id: '',
name: '',
image: '',
description: '',
price: {
relations: <PriceRelation[]>[ <PriceRelation>{ quantity: 0, price: 0, type: PriceRelationType.nForX }],
scale: 0
}
})
import { Record } from 'immutable'
export enum PriceRelationType {
nForX,
nForPriceOfX
}
export interface PriceRelation {
type: PriceRelationType
quantity: number
price: number
}
export interface ProductType {
id: string
name: string
image: string
description: string
price: {
relations: PriceRelation[]
scale: number
}
}
export const ProductRecord: Record.Factory<ProductType> = Record({
id: '',
name: '',
image: '',
description: '',
price: {
relations: [{ quantity: 0, price: 0, type: PriceRelationType.nForX }],
scale: 0
}
})
对于给定的代码块,Typescript 通过给出以下错误拒绝编译它
Types of property 'price' are incompatible.
Type '{ relations: PriceRelation[]; scale: number; } | undefined' is not assignable to type '{ relations: { quantity: number; price: number; type: PriceRelationType.nForX; }[]; scale: number; } | undefined'.
Type '{ relations: PriceRelation[]; scale: number; }' is not assignable to type '{ relations: { quantity: number; price: number; type: PriceRelationType.nForX; }[]; scale: number; }'.
枚举值似乎有问题,删除它可以修复错误。
我怀疑显式输入关系数组可以解决这个问题,例如:
export const ProductRecord: Record.Factory<ProductType> = Record({
id: '',
name: '',
image: '',
description: '',
price: {
relations: <PriceRelation[]>[ <PriceRelation>{ quantity: 0, price: 0, type: PriceRelationType.nForX }],
scale: 0
}
})