小编Yur*_*yuk的帖子

TS2322:类型 '{ [x:字符串]:字符串;}' 不可分配给类型“Record”。打字稿通用

我对打字稿通用有疑问

代码:

type ValidationError<S> = Record<keyof S, string>;

function validateType<S>(
  key: keyof S,
  value: string,
  type: FieldType | FieldType[],
  errors: ValidationError<S>[],
): void {
  switch (type) {
    case 'email': {
      if (!validator.isEmail(value)) {
        const error: ValidationError<S> = {
          [key]: 'error!',
        };

        errors.push(error);
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但我有打字稿错误“TS2322:类型 '{ [x: string]: string; }' 不可分配给类型 'Record '。” 关于:

const error: ValidationError<S> = {
  [key]: 'error!',
};
Run Code Online (Sandbox Code Playgroud)

有人可以描述为什么会发生错误以及如何修复它吗?

typescript typescript-generics

5
推荐指数
1
解决办法
5771
查看次数

标签 统计

typescript ×1

typescript-generics ×1