3

Is it possible to have a self-referenced type representation like this?

export type SelfReferenced {
    prop: string;
    [x: string]: SelfReferenced;
}

It means that all keys will be a reference of this except prop field Ex:

const $deep: SelfReference = createProxy();
let lastReference = $deep.a.very.long.nested.deep; //type: SelfReference
lastReference.prop //type: string

Additional requirement is using generic type parameter in prop:

export type SelfReferenced<T> {
    prop: () => T;
    [x: string]: SelfReferenced<T>;
}
Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
Pedro Mora
  • 375
  • 1
  • 4
  • 16
  • The problem I see is that `prop` key is of type string & then `[x: string]` will conflict. If you can make one of these key types something else then it'll work or I guess inherit the other part? – MiKr13 Nov 06 '21 at 13:44
  • You can make a self reference easily, but you can't make one where the `prop` property is incompatible with all the other properties. See https://stackoverflow.com/questions/61431397/how-to-define-typescript-type-as-a-dictionary-of-strings-but-with-one-numeric-i for various workarounds – jcalz Nov 06 '21 at 18:39
  • [Here](https://tsplay.dev/WyOvxN) is the code from the answer there translated to this example. – jcalz Nov 06 '21 at 18:46

1 Answers1

2

It could be represented by intersection:

type SelfReferenced = {
    prop: string;
} & { [x: string]: SelfReferenced; }

Playground


Update: Workaround for self-referencing recursive type with generics:

interface _SelfReferenced<T> { [x: string]: SelfReferenced<T>; }
type SelfReferenced<T> = _SelfReferenced<T> & { prop: () => T }

Playground

Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
  • Thanks, Things is I as trying with generic but there must be some bug which it doesn't allow to make it work deep.. like [here](https://www.typescriptlang.org/play?#code/C4TwDgpgBAyhA2AzAShREBOEB2BjCAJgDwAqAfFALxQDeAUFI1GBgPZgBcUAzsBgJbYA5gG46AXygAyWlADaADy68BwgLpc4SVOix5CpMiKji6dAhFzwAhlii5W2XlAAkFiJ1gIUaTDnzENPwEHNgArgC2AEaY4kZ08BDAUDa8On76VK7uYAB01rkAbpggufCOQrnYELyEuTnGAPSNoJCa3ul6+AnWab5dELks7FDNrRDKfIJCQA) – Pedro Mora Nov 06 '21 at 19:28
  • @PedroMora in linked example it is not clear what generics is used for – Aleksey L. Nov 07 '21 at 06:38
  • 1
    Let's say instead `prop: string` I have a method wich returns an `obj instanceof GenericType` – Pedro Mora Nov 07 '21 at 12:29
  • 1
    @PedroMora here's a workaround https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgPoGUIBsYCUIzQQhIAmAPACoB8yA3sgNoAeAXMgM5hSgDmAuu0w58hKMTJVqAbmQBfAFBgAngAcUwvASIkIFGsgC8aTaJ2SDAMmT4EAeygUA5Kqh3VTgDTIAFAEojWhoFBVIIBCw4cWR7EC5kABIwiFUhbC0xCT1yOmBSVhAAVwBbACNoORkFLAgwZEiuM3FdI0Tk1QA6OA6AN2hlDqw7EF4OkAguPQ722QB6WZV1NJFtZqRquEbVrI7Xd38OvOR5xYh2IrLoIA – Aleksey L. Nov 07 '21 at 12:45