首页 > 解决方案 > 扩展 TypeScript 接口后将可选属性转换为必需属性

问题描述

我有以下内置接口,其中属性value标记为可选:

interface LiHTMLAttributes<T> extends HTMLAttributes<T> {
   value?: string | ReadonlyArray<string> | number | undefined;
}

我想扩展上述接口以转换value为必需的(强制)属性。以下是我这样做的方式:

export interface UiSidebarListItem extends React.LiHTMLAttributes<HTMLLIElement> {
  id: string;
  value: string | ReadonlyArray<string> | number | undefined;
  active?: boolean;
  className?: string;
  onClick?: () => void;
}

但是,我需要value使用 union as 再次定义属性的数据类型string | ReadonlyArray<string> | number | undefined

有没有更好的方法来做到这一点,而无需value再次指定属性的类型并从扩展接口派生其类型LiHTMLAttributes

标签: typescript

解决方案


推荐阅读