简体   繁体   中英

Extending 'generic' TypeScript interface

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, eg:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM