【发布时间】:2019-11-21 06:10:05
【问题描述】:
我在这种情况下,我不知道类型会是什么样子,无论是未定义的还是布尔值、字符串还是数字等。我正在开发一个库,它将解析一些字符串内容并返回用户使用“类型对象”描述的属性对象。
Type 是类型对象应该是什么样子的接口,它是这样的:
/**
* 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;
}
我为用户提供了 3 个遵循此接口的预定义“类型对象”(Number 作为 numberType,Boolean 作为 booleanType,String 作为 stringType)。用户可以使用这些类型从字符串中收集参数。
参数接口定义了如何在代码中指定参数。
/**
* 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),那么解析器知道input.args.name 肯定是一个字符串,但如果不需要,它可能是未定义的或字符串。
这有可能实现吗?
【问题讨论】:
标签: typescript typescript-typings