【发布时间】:2020-08-04 21:13:57
【问题描述】:
我正在通过将 Typescript 应用到我构建的验证库来学习使用它。
types.ts
export type Value = string | boolean | number | null | undefined;
export type ExceptionResult = {
__errorType: string;
__errorArgs: string[];
};
export type ValidationResult =
| [ExceptionResult]
| [undefined, Value]
| undefined;
export type Rules = {
always: (defaultValue: Value) => (value: Value) => ValidationResult;
[key: string]: (defaultValue: Value) => (value: Value) => ValidationResult;
};
字符串.ts
type ValueAlways = Extract<Value, string | undefined | null>;
type ValueOther = Extract<Value, string>;
export const rules: Rules = {
always: (defaultValue: ValueAlways) => (value: ValueOther) => {
if (defaultValue !== undefined && (value == null || defaultValue === value))
return [undefined, defaultValue];
if (typeof value !== "string" || value === "")
return [Exception("String", [])];
},
equal: (mustBe: ValueOther) => (value: ValueOther) => {
if (mustBe !== value) return [Exception("StringEqual", [mustBe])];
},
}
错误信息
Type '(defaultValue: ValueAll) => (value: ValueSpec) => [undefined, string | null] | [ExceptionResult] | undefined' is not assignable to type '(defaultValue: Value) => (value: Value) => ValidationResult'.
Types of parameters 'defaultValue' and 'defaultValue' are incompatible.
Type 'Value' is not assignable to type 'string | null | undefined'.
Type 'number' is not assignable to type 'string | null | undefined'.ts(2322)
types.ts(9, 2): The expected type comes from property 'always' which is declared here on type 'Rules'
我的想法是拥有一个包含我支持的所有类型的 Value 类型以及将其限制为我正在使用的类型的 ValueAlways 和 ValueOther 类型。但是,它一直抱怨 Value 和 ValueAlways / ValueOther 不兼容。
为什么会这样?为什么抱怨number?
【问题讨论】:
标签: javascript typescript types