【问题标题】:Typescript clarification on index types and mapped types关于索引类型和映射类型的打字稿说明
【发布时间】:2018-09-02 11:23:32
【问题描述】:

我有一个接口,它定义了一个可用于将命令行参数传递给应用程序的对象:

type argumentPrimitive = string | number | Date | boolean;

export type IApplicationArguments = {
    [key: string]: argumentPrimitive | argumentPrimitive[];
}

我还有一个接口,可以选择将值替换为具有有关该参数的配置信息的对象:

export type IApplicationArgumentsConfiguration<T extends IApplicationArguments> = {
    readonly [P in keyof T]?: T[P] | CommandOption<T[P]>;
}

在我处理这个的函数中,我想遍历这些值:

function parseCommands<T extends IApplicationArguments>(optionDefinition: IApplicationArgumentsConfiguration<T>): T {

    for (let propertyName in optionDefinition) {
        const propertyValue: argumentPrimitive | CommandOption<argumentPrimitive> =  optionDefinition[propertyName];
    }
}

这不会编译:

类型 'IApplicationArgumentsConfiguration[keyof T]' 不可分配给类型 'string |号码 |布尔值 |日期 |命令选项'。

完全错误的游乐场链接:

Typescript Playground

有没有办法将映射类型传递到迭代代码?

【问题讨论】:

  • 为什么propertyValue首先要显式类型注释?
  • 我传递这个值的函数需要它。我将显式放入以帮助调试。

标签: typescript


【解决方案1】:

问题是我忘记了数组的可能性。

将代码更正为:

export interface CommandOption<T> {
    sampleValue: T;
}

type argumentPrimitive = string | number | Date | boolean;

type argumentTypes = argumentPrimitive | argumentPrimitive[];

export type IApplicationArguments = {
    [key: string]: argumentTypes;
}

export type IApplicationArgumentsConfiguration<T extends IApplicationArguments> = {
    readonly [P in keyof T]: T[P] | CommandOption<T[P]>;
}

function parseCommands<T extends IApplicationArguments>(optionDefinition: IApplicationArgumentsConfiguration<T>) {

    for (let propertyName in optionDefinition) {
        const propertyValue: argumentTypes | CommandOption<argumentTypes> =  optionDefinition[propertyName];
    }
}

使其正确编译。

【讨论】:

    猜你喜欢
    • 2021-03-06
    • 2019-11-19
    • 2022-12-07
    • 2022-08-17
    • 1970-01-01
    • 2018-06-16
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多