typescript - 扩展“通用”TypeScript 接口
问题描述
考虑以下 TS 定义:
type GenericPropsWithChildren<T> = T & { children?: ReactNode };
没有错,type
但我想知道是否有interface
等价物?显然,可以将泛型传递到接口中,尽管这不是我所追求的,例如:
interface GenericPropsWithChildren<T> {
children?: ReactNode;
myProps: T; // not desired
}
这里的示例是在 React 代码的上下文中,但根本问题是基础 TS。
解决方案
接口的成员必须在声明时知道,在扩展中使用泛型类型参数违反了此规则。所以没有办法创建一个等效的通用接口。
如果您已经知道类型参数,您实际上可以在接口中继承类型别名。只要所有成员在声明时都是已知的,就可以:
import { ReactNode } from 'react'
type GenericPropsWithChildren<T> = T & { children?: ReactNode };
interface Concrete extends GenericPropsWithChildren<{ p: string }> {
}
推荐阅读
- bash - 如何在 git 中取消暂存已删除的文件?
- visual-studio - 需要使用 ssis 将 6000 万条记录从 table 导出到 csv
- java - 在循环中打印出梯子的对面
- node.js - 错误状态:平台不允许使用不安全的 HTTP:
- python - How do I rotate a PyTorch image tensor around it's center in a way that supports autograd?
- r - na.rm 不工作,无法计算平均值
- javascript - 如何使两个元素在同一个类中可拖动
- redux - 为什么我的方法不起作用?反应还原
- autodesk-forge - 使用 Forge API 翻译后,无法在 Autodesk Viewer 上显示翻译后的 .zip 文件
- php - 如何确定一个 php 对象是否代表一个顺序数组而不是关联字典?