我在我的项目中使用Vue和类型记录,当我试图验证我的表单时,我在返回函数时遇到问题。以下是错误:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: ((v: string) => string | true)[]; enrollment: ((v?: string) => Fn)[]; cpf: ((number: string) => string | true)[]; profession: ((v: unknown) => Fn)[]; admission_date: ((v: unknown) => Fn)[]; department: ((v: unknown) => Fn)[]; email: ((v: unknown) => Fn)[]; phone: ((v: unknown) => Fn)[]; }'. No index signature with a parameter of type 'string' was found on type '{ name: ((v: string) => string | true)[]; enrollment: ((v?: string) => Fn)[]; cpf: ((number: string) => string | true)[]; profession: ((v: unknown)
=> Fn)[]; admission_date: ((v: unknown) => Fn)[]; department: ((v: unknown) => Fn)[]; email: ((v: unknown) => Fn)[]; phone: ((v: unknown)
=> Fn)[]; }'.
和
Unsafe return of an `any` typed value.eslint@typescript-eslint/no-unsafe-return
我的代码:
const myRules = {
name: [
isPersonName('', t),
],
enrollment: [
eqLength('', 4, t)
],
cpf: [
isValidCpf(t),
],
profession: [isRequired('', t)],
admission_date: [isRequired('', t)],
department: [isRequired('', t)],
email: [isRequired('', t)],
phone: [isRequired('', t)],
}
这里正是我的错误发生的地方:
//@ts-ignore
const getMyRules = (item: string) => myRules[item]
我无法理解的是,如果我运行控制台,我的数据就会正确地显示在控制台中,但是当我试图返回这个值时,ESlint会给出错误。
//@ts-ignore
const getMyRules = (item: string) => console.log(fieldRules[item])
我的投入:
<component
v-for="field in getFields()"
v-bind="field.props"
:mask="addMaskInputs(field.name)"
:rules="getMyRules(field.name)"
/>
发布于 2022-05-03 12:46:14
在您发布的代码中,没有给出myRules
的类型定义,可能是类型记录无法推断从该对象获取某些内容的结果。如果您暗示item
参数的类型为keyof myRules
,则可能会有所帮助。
const myRules = {/* ... */};
const getMyRules = (item: keyof myRules) => myRules[item];
还请注意,我没有从“item”参数中删除| undefined
,因为如果允许传递未定义的内容,那么类型记录将使用getMyRules
返回myRules[undefined]
(可能是undefined
或运行时错误)。
如果使用可能未定义的变量调用getMyRules
,则应该首先修复那里的类型。您的类型系统将首先对最宽松的定义进行分解。
https://stackoverflow.com/questions/72099442
复制相似问题