1

我正在尝试构建一个系统来增强带有验证的 typedef。

export interface Struct {
  [key: string]: <T>(input: string) => T | DiplomacyError;
}
export type RawType<T extends Struct> = {
  [Property in keyof T]: ReturnType<T[Property]>;
};
const Person = {
  age: all<number>(isInteger, isNonNegative),
  name: all<string>(isString, matchesPattern(/^[a-z ,.'-]+$/)),
};
type RawPerson = RawType<typeof Person>;

为什么不type RawPerson等于{ age: number | DiplomacyError, name: string | DiplomacyError }我所期望的?

type RawPerson = { age: unknown, name: unknown }相反,它的结果是 。

all功能:

/**
 * @param typifier Determines the raw type.
 * @param assertions Predicates the value needs to "pass".
 * @returns Either "Cannot Decode" or the casted value.
 */
export const all = <T>(typifier: Typifier<T>, ...assertions: Assertor[]) => <T>(
  input: string
): T | DiplomacyError => {
  const parsedInput = typifier(input);

  if (parsedInput === "#!CD") {
    return "#!CD" as DiplomacyError;
  }

  for (let i = 0; i < assertions.length; i++) {
    if (assertions[i](parsedInput) === "#!CD") {
      return "#!CD" as DiplomacyError;
    }
  }

  return (parsedInput as unknown) as T;
};
4

0 回答 0