Home > Software design >  Right hand type assignment
Right hand type assignment

Time:10-19

I am working on converting a React application to TypeScript and have encountered an issue where a variable is assigned one of two values with differing types:

const day = days?.find(d => isSameDate(d.date, date)) || {};

If I just put the type on left side like so:

const day:Iday= days?.find(d => isSameDate(d.date, date)) || {};

I get an error when I try to access one of day's props as {} does not contain said prop. The TypeScript error I get is:

Property 'date' does not exist on type '{} | Idate'. 
Property 'date' does not exist on type '{}'.ts(2339)

when trying to access day.date.

What I want is something like:

const day = days?.find(d => isSameDate(d.date, date)):Iday || {}:Iempty;

Is something like this possible?

CodePudding user response:

You can use the union type, do it like this:

const day: Iday | {} = days?.find(d => isSameDate(d.date, date)) || {};

CodePudding user response:

A union type describes a value that can be one of several types. Use a |(vertical bar) to separate the types.

const day : Iday | Iempty = days?.find(d => isSameDate(d.date, date)) || {};

CodePudding user response:

If you want to be able to access day.date even when day is an empty object, you can use the type Partial<IDay>.

Partial<IDay> will make all properties of IDay optional, meaning that if your IDay type looks like this:

interface IDay {
  date: Date,
}

Partial<IDay> is equivalent to:

interface IDay {
   date?: Date
}

But chances are that this is not the best way to type your code. In your case, it may be better to type your variable as IDay | null for example:

const day = days?.find(d => isSameDate(d.date, date)) || null;

Then you could wrap the code trying to access the date field in a condition:

if (day !== null) {
   console.log(day.date)
}
  • Related