1

I have this response type

export interface IResponse {
  status: boolean;
  message: string;
}

Then I would like to pass a custom interface to this type.

const res: IResponse<{count: number}> = await ...

How to modify my type so that res.count is recognized?

3 Answers 3

2

You can declare a new generic type as an alias of an intersection type:

type CustomResponse<T> = IResponse & T

export function test() {
  const res: CustomResponse<{count: number}> = { }
  
  console.log(res.status) // true
  console.log(res.count)  // 1
}

Note that this approach will "lock" the type, as then CustomResponse is not an interface anymore and therefore can't be extended.

// Compile error
export interface A extends CustomType<string> {
}
Sign up to request clarification or add additional context in comments.

Comments

1

I'm not sure I understand what you want to do exactly, but if you want to extend an interface you can do it like so:

interface ExtendedResponse extends IResponse {
    count: number
}

Then you can use it as you would any other interface:

const res: ExtendedResponse = await ...

1 Comment

I can do that but passing the type on the fly is more flexible. I don't want to have to create an interface for each post request.
1

One option would be:

const res: IResponse<IResponse & {count: number}> = await ...

the second one @Hoff stated. You need to extend IResponse with your custom one

Although I think it would be better for you do do something like:

export interface IResponse {
  status: boolean;
  message: string;
}

export type TResponse<T> = IResponse & T;

export interface Count {
  count: number
}

const res: IResponse<Count> = await ...

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.