【问题标题】:Typescript - Pick only a value from another type's fieldTypescript - 仅从另一种类型的字段中选择一个值
【发布时间】:2023-02-15 22:59:01
【问题描述】:

我有一种类型,我只想从一个字段中选择一个值。类型看起来像这样:

export interface RoleDto {
    id: string;
    objectNumber: string;
    type: "BA" | "BM" | "BP" | "FR" | "RM";
}

我想从 RoleDto 中的类型值创建一个类型:

export type IRoleType = Pick<RoleDto, "roleType">;

它创建了一个初始类型:

{ rolleType: "BA" | "BM" | "BP" | "FR" | "RM" }

但是,我只想获得一个值,以便我可以将它用于我的组件道具,如下所示:

export const RoleTag = ({ roleType }: IRoleType) => 

有没有办法做到这一点?

【问题讨论】:

    标签: typescript


    【解决方案1】:
    interface RoleDto {
        id: string;
        objectNumber: string;
        roleType: "BA" | "BM" | "BP" | "FR" | "RM";
    }
    
    type IRoleType = Pick<RoleDto, "roleType">;
    type IRoleTypeValues = IRoleType["roleType"];
    
    const RoleTag = ({ roleType }: IRoleType) =>  console.log(roleType);
    const roleDTO: RoleDto = {id: "1", objectNumber: "1", roleType: "BA"}
    RoleTag(roleDTO);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      相关资源
      最近更新 更多