扩展“通用"TypeScript 接口 [英] Extending 'generic' TypeScript interface
问题描述
考虑以下 TS 定义:
Considering following TS definition:
type GenericPropsWithChildren<T> = T & { children?: ReactNode };
type
没有问题,但我想知道是否有等效的 interface
?显然,可以将泛型向下传递到接口,尽管这不是我所追求的,例如.:
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
}
这里的示例是在 React 代码的上下文中,但潜在的问题是基本的 TS.
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 }> {
}
这篇关于扩展“通用"TypeScript 接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!