首页 > 解决方案 > 如何在打字稿界面中使用多个键?

问题描述

我正在 React + TypeScript 环境中开发。

我想对“内容”键有多个键。

    interface IModalProps {
        isOpen: boolean;
        type: 'basic';
        content: ReactElement;
        options?: IModalOption;
}

我用下面的代码想象它。

interface IModalProps {
        isOpen: boolean;
        type: 'basic';
        [content | children]: ReactElement;
        options?: IModalOption;
}

上面的代码意味着键是“内容”或“孩子”。

有没有办法在类型脚本中有多个键?谢谢。

标签: typescript

解决方案


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'>

操场


推荐阅读