Having a structure like this:
enum Company {
Google,
Facebook
}
function getRating(company: Company) {
const ratingMap = {
[Company.Google]: 1000,
[Company.Facebook]: 2000
}
const result = ratingMap[company]
return result
}
TypeScript understands that result is a number. But if I list not all the Company values in the ratingMap, then the result has type any. I want ts to resolve this expression into number | undefined rather than any.
function getRating(company: Company) {
const ratingMap = {
[Company.Google]: 1000,
// [Company.Facebook]: 2000
}
const result = ratingMap[company] // Element implicitly has an 'any'
return result
}
I know I can set a type for ratingMap like this:
const ratingMap: Partial<Record<Company, number>>
and it would give me expected number | undefined. But I think there should be a simpler elegant solution. Maybe a specific tsconfig property.
Any ideas how to achieve this?