1

Has anyone been able to create typings for Immutable Map's getIn function that is typesafe?

Below is my attempt of creating typings for the it so that it works with recursive immutable maps.

import * as Immutable from 'immutable'

type ImmutableType = '0'
type PartialType = '1'
type PrimitiveType = '2'

type SchemaTypes = ImmutableType | PartialType | PrimitiveType
type Switch<Type extends SchemaTypes, K extends Schema<Type>> = {
  0: ImmutableExtra<K> & Immutable.Map<keyof K, any>
  1: Partial<K>;
  2: K
}[Type];

type ImmutableParent =  Switch<ImmutableType, ParentSchema<ImmutableType>>
let immutableParent: ImmutableParent
const childStringViaGet = immutableParent.get("child").get("childString") //typesafe. type is string 
//Can't figure out this part
const childStringViaGetIn = immutableParent.getIn(["child", "childString"]) //not typesafe. type is any. Can't figure it out

interface Schema<T extends SchemaTypes> {
}

export interface ImmutableExtra<T extends Schema<ImmutableType>> {
  get<K extends keyof T>(value: K): T[K]
  getIn<A extends keyof T>(keys: [A]): T[A]
  // Things I tried but doesn't work
  // getIn<A extends keyof T, B ChildImmutable extends T[A]>(keys: [A, B]): T[A]["get"]
  //getIn<A extends keyof T, B extends keyof T[A]>(keys: [A]): T[A][B]
  //getIn<A extends keyof T, B extends keyof ChildType, ChildType, ChildImmutable extends T[A] & ImmutableExtra<ChildType>>(keys: [A, B])
}

interface ParentSchema<T extends SchemaTypes> {
  parentString: string
  parentNumber: number
  child: Switch<T, ChildSchema<T>>
}

interface ChildSchema<T extends SchemaTypes> {
  childString: string
  childNumber: number
}
Sunny
  • 41
  • 6
  • I don't see a good answer online yet, but if you would like to gether more info, folks also have ideas and partial implementations at https://stackoverflow.com/questions/52824312/how-to-use-immutablejs-map-with-typescript – Dawson B Feb 08 '20 at 20:48

1 Answers1

0

Apparently this is not currently possible for the generic case, but you could overload it for a couple of tuple-lengths. See the related discussion here:

https://github.com/Microsoft/TypeScript/issues/12290

tobiasH
  • 411
  • 5
  • 11