在这种情况下,我不知道类型是什么样,无论是未定义的还是布尔值,字符串或数字等。我正在研究一个解析某些字符串内容并返回的库用户使用“类型对象”描述的属性对象。
res = http.request('GET',download_url,preload_content=False)
out_file = open(out_file,'wb')
shutil.copyfileobj(res,out_file)
是类型对象外观的接口,它像这样:
Type
我已经为用户提供了3个预定义的“类型对象”,它们遵循此界面(数字作为numberType,布尔作为booleanType,字符串作为stringType)。用户可以使用这些类型从字符串中收集参数。
参数接口定义应如何在代码中指定参数。
/**
* A type object.
*/
export default interface IType<O>
{
/** The name of the type. */
name: string;
/** A description of the type. */
description?: string;
/**
* Parse the given input content and return the parsed output value.
* @param input The given input value.
* @returns The parsed output.
*/
parse(input: string): O;
}
用户创建命令类,并将一些参数传递给构造函数,包括参数数组;
/**
* An object describing how an argument will look like.
*/
export default interface IArg<T>
{
/**
* The name of the argument,this is how you use the argument later
* in the command object.
*/
name: string;
/** A description about the argument. */
description?: string;
/** The type the argument should be resolved with. */
type: IType<T>;
/** Should this take all the parameters left of the string? */
rest?: boolean;
/** Is the argument required? */
required?: boolean;
}
解析命令字符串时,这些参数将添加到对象[
{
name: "age"
type: numberType
},{
name: "name",type: stringType
}
]
中。我想以某种方式让打字稿解析器知道用户提供的信息可能会或可能不会提供什么。
例如如果参数是必需的并且是input.args
的类型(我们将其称为IArg<string>
),则解析器会知道name
绝对是字符串,但是如果不需要,则可能是未定义的或字符串。
这有可能实现吗?
编辑:我发现了this的jcalz答案,该答案带有一个键值对对象,该对象正是我所要寻找的;但是我不确定如何使用数组来实现它。