I want to be able to restrict the type of key values in an object, based in the type of the key. However, the type of the key is a string interpolation type.
What I want is any value in the object whose key includes an asterisk * should be (for sake of example) a number, and any other key should be a string.
const routes = {
'some/route': 'a string',
'with/a/*': 2
}
I have made a generic to check if a string has an asterisk which works well:
type IncludesAstrix<S> = S extends `${infer F}*${infer T}` ? true : false;
I can see it working:
type Truthy = IncludesAstrix<'with/a/*'> // true
type Falsey = IncludesAstrix<'no/asterisk'> // false
But it doesn't work when used with a key in an object:
type RoutesObject = {
[K in string]: IncludesAstrix<K> extends true ? number : string;
};
With this, I'd expect this to error, but it doesn't:
type IncludesAstrix<S> = S extends `${infer F}*${infer T}` ? true : false;
type RoutesObject = {
[K in string]: IncludesAstrix<K> extends true ? number : string;
};
const routes: RoutesObject = {
'some/route': 'a string',
'with/a/*': 'should not be string!' // this should error?
}
What am I doing wrong? Is this even possible?