Type that converts all strings to function that returns string

I have an object like
{
foo: 'hey'
bar: {
bar1: 'sup'
bar2: {
bar3: 'love you'
}
}
}
{
foo: 'hey'
bar: {
bar1: 'sup'
bar2: {
bar3: 'love you'
}
}
}
I want to create a type that converts all the strings to functions that return strings. For example, typeof bar.bar2.bar3 = () => "love you" I have no idea how to do this lol
17 Replies
Froxx
Froxx•3y ago
I guess what you want to create is a function, not a type. So you would need a recursive function that does following things: 1. check if passed parameter is a primitive (string, or maybe number, bool, ...), if so return "() => parameter" 2. if param is array, map through it and call itself with each item as the new parameter 3. if param is object, map do the same for all objects props ( Object.keys(obj) )
benton
bentonOP•3y ago
I'm actually trying to lie to the compiler about the type It's not actually a function that returns a string, but I want tsc (and autocomplete) to think it is
barry
barry•3y ago
type Stringify<E> = { [K in keyof E]: () => E[K] };
type Stringify<E> = { [K in keyof E]: () => E[K] };
something like this im not sure, not a wizard
Froxx
Froxx•3y ago
Oh alright. Then I'm out as well 😅 I would generally recommend using the Record<key, value> syntax instead of { [key]: value }. A bit more clear imo
benton
bentonOP•3y ago
This will cast bar as a string when it should be an object I tried Omit<Record<string, string>, keyof typeof myObject> but it didn't work The part I'm stuck on is only casting the strings, not the objects
barry
barry•3y ago
const E = {
foo: "one",
bar: {
one: "bar",
two: "baz",
}
} as const;

type barrystype<T> = {
[K in keyof T]: T[K] extends string ? () => T[K] : barrystype<T[K]>
}
const E = {
foo: "one",
bar: {
one: "bar",
two: "baz",
}
} as const;

type barrystype<T> = {
[K in keyof T]: T[K] extends string ? () => T[K] : barrystype<T[K]>
}
maybe that will work as const is important
benton
bentonOP•3y ago
sadly not
barry
barry•3y ago
it should
benton
bentonOP•3y ago
benton
bentonOP•3y ago
global and home are objects
barry
barry•3y ago
works for me
barry
barry•3y ago
oh no kinda
benton
bentonOP•3y ago
wait it does work vscode shows it as strings when you hover, but it doesn't complain when you invoke it
benton
bentonOP•3y ago
benton
bentonOP•3y ago
thanks barry you a g
barry
barry•3y ago
dont thank me thank some dude on typescript discord lol InfectiousFight#0245
Unknown User
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View

Did you find this page helpful?