Raghav Soni
Raghav Soni

Reputation: 21

How to declare a type in typescript based on the keys mentioned in the same type?

I want to declare a type in typescript ApiResponse and mention 3 keys in it which are isError, error, and content. What I want is that type should be declared as such that either isError and error exist or content exists.

type ApiResponse<T> = {
    isError?: boolean;
    error?: ErrorContent;
    content: this.isError ? undefined : User; // this is something I want . how should I do it.
}

I want this so that when I call a function which wants a parameter of User type doesn't give an error that the parameter is undefined

Upvotes: 1

Views: 60

Answers (2)

Raja Jaganathan
Raja Jaganathan

Reputation: 36127

We can't define type based on dynamic value here,

  1. one we need to use generic to get User type
  2. Instead of isError boolean we should use status kind of enumeration (success, error)

so that we represent invalid state properly. Try like below,

type ErrorContent = {};
type User = {};

interface SuccessResponse<T> {
  status: "success";
  content: T; // this is something I want . how should I do it.
}

interface ErrorResponse {
  status: "error";
  error: ErrorContent;
}

type ApiResponse<T> = SuccessResponse<T> | ErrorResponse;

const success: ApiResponse<User> = {
  status: "success",
  content: {}
};

const failure: ApiResponse<User> = {
  status: "error",
  error: {},
};

Upvotes: 1

michael
michael

Reputation: 4173

It is impossible to define type differently by variable. Simply you can define the type using | operator.

type ApiResponse<T> = {
  isError?: boolean;
  error?: ErrorContent;
  content: User | undefined;
}

Upvotes: 1

Related Questions