3

Let's say I have an interface like the below:

interface IProps<T> {
   property: T
}

How can extend the above interface, something like below,

interface IPropChild<U> extends IProps {
       propertyChild: U
   }

I know that the above syntax is wrong. Can you provide the right way to accomplish it. Thanks in advance.

1
  • Can you explain exactly what you want to accomplish? Is U completely independent of T? So then does interface PropChild<T, U> extends IProps<T> {propertyChild: U} meet your needs? If not, then please elaborate on what's missing. Commented Jan 19, 2022 at 15:56

1 Answer 1

4

You can accept two generic type parameters and forward one to the interface that you extend:

interface Props<T> {
  property: T;
}

declare const props1: Props<string>;
props1.property; // string

// Forward the generic parameter T to the generic interface that it extends:
interface Extended<T, U> extends Props<T> {
  another: U;
}

declare const props2: Extended<string, number>;
props2.property; // string
props2.another; // number

Or, make the base interface generic type fixed when using the extending interface:

// Only use one generic parameter and decide in advance that
// this interface will always use `string` for the base interface:
interface ExtendedAndPropertyIsString<U> extends Props<string> {
  another: U;
}

declare const props3: ExtendedAndPropertyIsString<number>;
props2.property; // string
props2.another; // number

TS Playground

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.