I have a string with text separated by periods. It can contain any number of periods, for example:
const sampleString1 = "a.b";
const sampleString2 = "a.b.c.d";
I am looking to create a generic type in TypeScript called StringToNestedObject
that will take a string like this and return a nested object type as follows:
type Type1 = StringToNestedObject<typeof sampleString1>;
// Type1 should be: { a: { b: string; } }
type Type2 = StringToNestedObject<typeof sampleString2>;
// Type2 should be: { a: { b: { c: { d: string; } } } }
The closest solution I have come up with for StringToNestedObject
is:
type StringToNestedObject<S extends string> =
S extends `${infer First}.${infer Rest}` ? {
[First]: StringToNestedObject<Rest>
} : {
[S]: string
};
However, there are errors because [First]
and [S]
do not work due to:
A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.(1170)
'T' only refers to a type, but is being used as a value here.(2693)
Click here for a TypeScript playground with the code.
(This task is inspired by how IndexedDB key paths use strings separated by periods to represent nested objects.)