[英]Typescript Conditional Types combined with mapped types documentation example clarification
[英]Typescript clarification on index types and mapped types
我有一个定义一个对象的接口,该对象可用于将命令行参数传递给应用程序:
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 | 编号 布尔| 日期| CommandOption”。
游乐场链接出现完整错误:
有没有办法将映射的类型传递给迭代代码?
问题是我忘记了数组的可能性。
将代码更正为:
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];
}
}
使其正确编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.