首页 > 解决方案 > 扩展“通用”TypeScript 接口

问题描述

考虑以下 TS 定义:

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

没有错,type但我想知道是否有interface等价物?显然,可以将泛型传递接口中,尽管这不是我所追求的,例如:

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

这里的示例是在 React 代码的上下文中,但根本问题是基础 TS。

标签: typescripttypescript-generics

解决方案


接口的成员必须在声明时知道,在扩展中使用泛型类型参数违反了此规则。所以没有办法创建一个等效的通用接口。

如果您已经知道类型参数,您实际上可以在接口中继承类型别名。只要所有成员在声明时都是已知的,就可以:

import { ReactNode } from 'react'

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

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

}

游乐场链接


推荐阅读