Typescript:泛型不可变集合

Typescript: generic immutable collections

本文关键字:集合 不可变 泛型 Typescript      更新时间:2023-09-26

我有以下定义(我使用的是ImmutableJS):

declare module Immutable {
    export module Record {
        type IRecord<T> = T & TypedMap<T>;
        interface TypedMap<T> extends Map<string, any> {
            set(key: string, value: any): IRecord<T>
        }
        interface Factory<T> {
            new (): IRecord<T>;
            new (values: T): IRecord<T>;
            (): IRecord<T>;
            (values: T): IRecord<T>;
        }
    }
    export interface Record<T> {
        (defaultValues: T, name?: string): Record.Factory<T>;
    }
    export function Record<T>(
        defaultValues: T, name?: string
    ): Record.Factory<T>;
}
declare interface IState extends Immutable.Map<string, any> {
    router: Immutable.Map<string, any>;
    sessions: Immutable.Map<gameId, Immutable.List<Immutable.Record<ISession>>>;
    games: Immutable.Map<gameId, Immutable.Record<IGame>>
}

当我这样使用它时:

const state: IState = <IState>Map<string, any>({
    router: Map<string, any>(),
    sessions: Map<gameId, List<Record<ISession>>>({
        1: List([10])
    }),
    games: Map<gameId, Record<IGame>>()
});

我没有任何错误。我想它会抱怨这个部分:

sessions: Map<gameId, List<Record<ISession>>>({
    1: List([10])
})

我在List<Record<ISession>> 中添加了数字10

为什么我没有看到任何错误?

这不是一个真正的答案,但它不适合放在评论框中。

@Sohnee,关于你在上面评论中的问题,@popoliani正在从Immutable.js扩展类型,所以这就是Map(以及List和Record)的来源。

我想知道TS 1.7的"this"功能是否与答案相关:多态"this"类型的Typescript PR。我认为Immutable.js的人仍然在思考如何处理Records中的类型安全和继承。见证

  • 提出了类型调整,以改进TypeScript代码中Record实例的使用
  • 建议:接口扩展泛型类型

在他们思考这一点的同时,我也在思考记录是否值得它们带来的类型安全挑战。