#inferring types from string

6 messages · Page 1 of 1 (latest)

ivory spear
#

hey! i'm almost certain this is 100% impossible, but i'd like to ask anyway. say i have a string with "templates" defined like {{TEMPLATE_NAME}}. is it possible to write a function with types regarding the templates included in the string? for example:

doSomething("Hello, {{NAME}}", { 
    // right here, there would be a property called "name" or "{{NAME}}" or something
});```

again, almost certain this is not possible, but would love to be proven wrong
#

oh no way its actually possible

#

give me a minute

#
type ExtractPlaceholders<T extends string> = T extends `${infer _Start}{{${infer Placeholder}}}${infer Rest}`
  ? Placeholder | ExtractPlaceholders<Rest>
  : never;

type CreateObjectType<T extends string> = {
  [K in ExtractPlaceholders<T> as Lowercase<K>]: string
};

type ExampleString = "Hello, {{NAME}}, you are {{AGE}} years old.";

type ResultType = CreateObjectType<ExampleString>;```

TS has come a long way. this is mental
stoic bane
ivory spear
#

this code was generated by llama3:8b lol