I am trying to define a type that can receive any type that is an object and it returns a type that only accepts dotted paths (prop1.prop2.prop3) to string or string[]. So far this is what I have:
type MyType<ObjectType extends Record<string, unknown>> = {
[Key in keyof ObjectType & string]: ObjectType[Key] extends Record<
string,
unknown
>
? MyType<ObjectType[Key]> extends ""
? ""
: `${Key}.${MyType<ObjectType[Key]>}`
: ObjectType[Key] extends Array<Record<string, unknown>>
? MyType<Unpacked<ObjectType[Key]>> extends ""
? ""
: `${Key}.${MyType<Unpacked<ObjectType[Key]>>}`
: ObjectType[Key] extends Array<string> | string
? `${Key}`
: "";
}[keyof ObjectType & string];
The bad thing is that this type also returns the parent prop of a prop that is of type string or string[]. For example, if a have the following type:
type ExampleType = {
detail: {
prop1: string;
subDetail: {
field1: string;
field2: number;
field3: {
inner: string[];
};
field4: number[];
};
};
arrOfObjs: {
name: string;
age: number;
ages: number[];
}[];
};
Then MyType<ExampleType> incorrectly accepts arrOfObjs. and detail.subDetail., but it accepts, as expected: arrOfObjs.name, detail.prop1, detail.subDetail.field1 and detail.subDetail.field3.inner.
Can anyone point out what I'm missing? Thank you in advance for your time.