5

Considering following TS definition:

type GenericPropsWithChildren<T> = T & { children?: ReactNode };

Nothing wrong with type but I wonder if there is an interface equivalent? Obviously it is possible to pass generics down into interfaces though that is not what I am after, e. g.:

interface GenericPropsWithChildren<T> {
 children?: ReactNode;
 myProps: T; // not desired
}

The examples here are in a context of React code but the underlying issue is fundamental TS.

1 Answer 1

2

An interface's members must be known at declaration, using a generic type parameter in the extends violates this rule. So there is no way to create an equivalent generic interface.

If you already know the type parameter you can actually inherit a type alias in an interface. As long as all members are known at declaration it is allowed :

import { ReactNode } from 'react'

type GenericPropsWithChildren<T> = T & { children?: ReactNode };

interface Concrete extends GenericPropsWithChildren<{ p: string }> {

}

Playground Link

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

1 Comment

Cheers, I suspected this would be the case and should go on the list of the main differences between type and interface.

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.