Home > Blockchain >  Typescript - Self reference with generic property
Typescript - Self reference with generic property

Time:11-08

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>;
}

CodePudding user response:

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

  • Related