typescript - 如何在打字稿界面中使用多个键?
问题描述
我正在 React + TypeScript 环境中开发。
我想对“内容”键有多个键。
interface IModalProps {
isOpen: boolean;
type: 'basic';
content: ReactElement;
options?: IModalOption;
}
我用下面的代码想象它。
interface IModalProps {
isOpen: boolean;
type: 'basic';
[content | children]: ReactElement;
options?: IModalOption;
}
上面的代码意味着键是“内容”或“孩子”。
有没有办法在类型脚本中有多个键?谢谢。
解决方案
import { ReactElement } from 'react'
type IModalOption = {
tag: 'IModalOption'
}
interface Props {
isOpen: boolean;
type: 'basic';
options?: IModalOption;
}
type Union<T extends string> = T extends string ? Record<T, ReactElement> : never
type IModalProps = Props & Union<'content' | 'children'>
// error, there are no 'content' and/or 'children'
const props: IModalProps = {
isOpen: true,
type: 'basic',
options: {
tag: 'IModalOption'
},
}
// ok
const props2: IModalProps = {
isOpen: true,
type: 'basic',
options: {
tag: 'IModalOption'
},
content: null as any as ReactElement
}
// ok
const props3: IModalProps = {
isOpen: true,
type: 'basic',
options: {
tag: 'IModalOption'
},
children: null as any as ReactElement
}
// ok
const props4: IModalProps = {
isOpen: true,
type: 'basic',
options: {
tag: 'IModalOption'
},
children: null as any as ReactElement,
content: null as any as ReactElement
}
Union
实用程序类型分布 content | children
。
这意味着它适用于每个工会。Union<'content' | 'children'>
返回Record<'content, ReactElement> | Record<'children, ReactElement>
。
为了实现所需的行为,您只需要将基本道具与联合合并:
type IModalProps = Props & Union<'content' | 'children'>
推荐阅读
- c# - 为什么 Bunifu 控件在 this.Close() 上显示错误
- angular - Mmenu.js 与 Angular 框架的集成
- google-chrome - Chrome 扩展程序拒绝
- java - 将捕获图像数据插入片段中的 ImageView 时出错
- reactjs - 将数字传递给反应js中的函数
- python - 我收到此错误---> TypeError: integer argument expected, got float
- sendgrid - Sendgrid 的链接产生无法建立安全连接
- windows - 在 ubuntu 上解压后文件名错误
- node.js - 如何在 Nestjs 中将 axios 内容从“text/html”更改为 application/json 类型
- java - Recyclerview 和 OkHttp 请求同步