【发布时间】:2021-03-29 04:35:54
【问题描述】:
假设我有以下辅助函数:
type Entity = Readonly<{ id: string }>
type EntityEntry<T extends Entity> = readonly [string, T| null]
export const toEntityMap = <T extends Entity>(ids: ReadonlyArray<string>) => {
return (entities: ReadonlyArray<T>): ReadonlyMap<string, T | null> => {
return new Map(
ids.reduce(
(acc: ReadonlyArray<EntityEntry<T>>, cur) => {
const entity = entities.find(e => e.id === cur)
const entry: EntityEntry<T> = [cur, entity ?? null]
return [...acc, entry]
}, []
)
)
}
}
我尝试这样称呼:
type Thing = Readonly<{
id: string,
foo: string
}>
export type ThingIds = Readonly<{
ids: ReadonlyArray<string>
}>
type GetThings = (thingIds: ThingIds) => TaskEither<Error, ReadonlyArray<Thing>>
export type Input = Readonly<{ ids: ReadonlyArray<string> }>
export type Result = ReadonlyMap<string, Thing | null>
type Deps = Readonly<{ getThings: GetThings }>
type Ctx = ReaderTaskEither<Deps, Error, Result>
export const execute = (input: Input): Ctx => (
(deps: Deps): TaskEither<Error, Result> => (
pipe(
deps.getThings(input),
map((things) => {
const map: ReadonlyMap<string, Thing | null> = toEntityMap(input.ids)(things)
return map
})
)
)
)
可运行链接: https://stackblitz.com/edit/typescript-tv6w7o
我希望它能够成功编译,因为 Thing 扩展了 Entity。但是,我得到了一个编译错误:
Type 'ReadonlyMap<string, Readonly<{ id: string; }>>' is not assignable to type 'ReadonlyMap<string, Readonly<{ id: string; foo: string; }>>'.
Property 'foo' is missing in type 'Readonly<{ id: string; }>' but required in type 'Readonly<{ id: string; foo: string; }>'.(2322)
表明由于某种原因我的实用程序函数正在将地图返回到实体。
我的问题是,为什么?我该如何解决这个问题?
【问题讨论】:
-
看起来,输入 asre 不兼容。看这里:typescriptlang.org/play?#code/…
-
不保证
toEntityMap将返回带有foo键的地图