I have a class that has a property fruits that is Record that maps a Fruit to an object.
type Fruit = 'Orange' | 'Apple' | 'Banana';
class FruitHandler {
fruits: Record<Fruit, Object>;
constructor() { this.fruits = {} /* 1st error */ }
public createFruit(fruit: Fruit): Object {
if (this.fruits[fruit]) return this.fruits[fruit] /* 2nd error */
const _fruit = new Object();
this.fruits[fruit] = _fruit;
return _fruit
}
}
The issue I am having is that when I initialise the fruits property, I get the following error:
Type '{}' is missing the following properties from type 'Record<Fruit, Object>': Orange, Apple, and Banana.
If I change the property of fruits to be Partial, i.e. fruits: Partial<Record<Fruit, Object>>, I get a different when I try to return the object associated in the fruit:
Type 'Fruit | undefined' is not assignable to type 'Fruit'.
Type 'undefined' is not assignable to type 'Fruit'
I'm clearly not understanding something.
Would somebody be able to explain what it is that I am missing? And how I might be able to go about implementing what it is that I am looking for: a Record with varying number of values, without having to implement each and every Type that I have typed as its Key.
EDIT: I have a working - but not ideal - solution:
private fruits: Partial<Record<Fruit, Object>>;
...
public createFruit(fruit: Fruit): Object {
if (this.fruits[fruit]) return this.fruits[fruit] as Fruit;
This has gotten rid of the error, but it obviously isn't something I want to do if it can be helped.