I have a function that takes a json key as a parameter. In order to allow autocompletion, I have typed this parameter. It works.
However, if I write the key with dynamic value, ex: CAR.BRAND.${color}
, typescript recognises it as an invalid string, that doesn't match the required schema.
How to allow random strings as a parameter while keeping the autocompletion?
Here is the code:
// json
{
hello: "hello",
world: "world",
name: {
john: "john",
doe: "doe"
}
}
// .ts file
type KeyPrefix<T extends string> = T extends "" ? "" : `.${T}`;
export type KeyPath<T> = (
T extends object
? {
[K in Exclude<keyof T, symbol>]: `${K}${KeyPrefix<KeyPath<T[K]>>}`;
}[Exclude<keyof T, symbol>]
: ""
) extends infer D
? Extract<D, string>
: never;
type Path = KeyPath<typeof myjson>;
function foo(key: Path){
return key
}
// expected output:
foo("nam") // autocomplete suggestions: name.john, name.doe.
foo("name.doe") // no error.
foo("name." + value) // no error. (currently returns an error)
I've tried to allow a random string entry like this:
type i18nSchema<T> = T & { [key: string]: string };
type Path = KeyPath<i18nSchema<typeof myjson>>;
It removes the error, but the autocompletion is gone.
How to fix this?