0

I have a code where I have these interfaces and type defined:

export interface ReportItem {
    title: string;
    earnings: number;
}

export interface CustomError {
    errorRaw: any;
}

export type SalesReport = ReportItem[];

Then I have a method that accepts a parameter, which may be of type SalesReport, but might also be a CustomError:

public getReport(data: SalesReport | CustomError) {
   if ('errorRaw' in data) {
       data.errorRaw // error
   }
}    

The reference to errorRaw field in data throws an error. What change do I need to make so it would work properly?

Thanks.

1 Answer 1

1

You're looking for a type guard to "narrow" your interface.

function isCustomErro(x: any): x is CustomError {
  return x.hasOwnProperty('errorRaw');
}

Then, you getReport method will look like this:

public getReport(data: SalesReport | CustomError) {
  if (isCustomError(data)) {
   throw new Error(data.errorRaw)
  }
}

Read more about type guards and narrowing interfaces here: https://medium.com/@OlegVaraksin/narrow-interfaces-in-typescript-5dadbce7b463

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.