I have a simple code:
const allTypes = { jpg: true, gif: true, png: true, mp4: true };
const mediaType = url.substring(url.lastIndexOf(\'.\') + 1).toLowerCas
You can use indexable types, but this widens the type of allTypes
to contain any (string) key, when it looks like you have a limited list of keys that you want to support.
A better solution - allowing you to use the proper type of allTypes
- is (as you already indicated in your question) to tell the compiler your assumption that mediaType
is one of the keys of the type of allTypes
with a type assertion:
return Boolean(allTypes[mediaType as keyof typeof allTypes]);
This type is in this case equivalent to the union type
"jpg" | "gif" | "png" | "mp4"
, but it is computed automatically.
(How you ensure that your assumption is correct at runtime is a separate concern, of course.)