#How would you create a recursive type for use as a generic type constraint?

2 messages · Page 1 of 1 (latest)

queen lily
#

Here's my example:

type MyBaseType = {
    [x: string]: string | number | MyBaseType;
};

type MyRecordType = Record<string, string | number | MyRecordType>; // fails with self-reference

function testGeneric<T extends MyBaseType>(input: T) {
    return null;
}

interface MyTestType {
    foo: string;
}

const testValue: MyTestType = { foo: "bar" };
testGeneric(testValue); // fails with missing index signature

This strategy works with T extends Record<string, ...> but I can't use Record to define a recursive type here.

My goal is to limit the objects provided to this function to only those that have values which are in limited set of types, or are objects that map string keys to the same limited set of types, or... recursive to an arbitrary depth.

#

fixed:

type MyValueType = string | number | { [key: string]: MyValueType };

function testGeneric<T extends { [K in keyof T]: MyValueType }>(input: T) {
    return null;
}

interface MyTestType {
    foo: string;
    bar: {
        yolo: string;
    };
}

const testValue: MyTestType = { foo: "bar", bar: { yolo: "baz" } };
testGeneric(testValue);