【问题标题】:Typescript issues: Restricted property types incompatible打字稿问题:受限制的属性类型不兼容
【发布时间】: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 类型以及将其限制为我正在使用的类型的 ValueAlwaysValueOther 类型。但是,它一直抱怨 Value 和 ValueAlways / ValueOther 不兼容。

为什么会这样?为什么抱怨number

【问题讨论】:

    标签: javascript typescript types


    【解决方案1】:

    问题在于 Function 属性必须包含其原型的所有类型。

    这很重要,因为如果您有 Rule,打字稿可能不知道是哪一种,因此 Rules.always(12) 必须始终正确 - 因此 rules.always(12) 也必须是可能的。

    您可能正在寻找 Conditional Types 和/或 Generics - 但这确实取决于您的用例

    【讨论】:

      猜你喜欢
      • 2018-11-18
      • 2017-12-12
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 2017-03-02
      • 2021-09-07
      • 1970-01-01
      相关资源
      最近更新 更多