Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Self reference with generic property

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>;
}
like image 342
Pedro Mora Avatar asked Sep 26 '26 22:09

Pedro Mora


1 Answers

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

like image 139
Aleksey L. Avatar answered Sep 28 '26 13:09

Aleksey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!