是否可以关闭某些功能的类型检查

Is it possible to turn off type check for certain functions

我有一个装饰器:

return function (target: any, propertyKey: string, descriptor: PropertyDescriptor): void {
        const originalMethod = descriptor.value

        if (!schema) return originalMethod

        schema(types)

        descriptor.value = function (...args: any[]) {
            return originalMethod.apply(this, args)
        }
    }

然后我像这样启动架构:

@endpoint({ 
    schema: (types) => ({
        test: 'test',
        test2: 'test2',
    })
})

我总是需要分配类型:

是否有可能以某种方式指定它可能在装饰器中或任何其他方式来避免它而不使用 // @ts-ignore

更新

这是装饰器声明

export function endpoint({ schema }: { schema: any, path?: string }) {
    
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor): void {
        const types: any = Joi.types()
        const originalMethod = descriptor.value

        if (!schema) return originalMethod

        descriptor.value = function (...args: any[]) {
            const context: any = { ...this, ...target, methodName: propertyKey }

            try {
                const { error } = schema.call(context, types, Joi).validate(args[0], { abortEarly: false })

                if(error) {
                    return {
                        type: 'ValidationError',
                        code: 422,
                        errors: error.details.map((err: any) => err.message)
                    }
                }
    
            } catch(err: any) {
                return {
                    type: 'InternalError',
                    code: 500,
                    errors: err.message,
                }
            }

            return originalMethod.apply(this, args)
        }
    }
}

我现在这样使用它,我总是需要提供类型,但我想这样做以节省时间,因为我已经知道应该 100% 的类型,也许有一个选项可以将类型设置为该特定位置的预定义类型。

它肯定会让代码更短,开发体验更快

    @endpoint({
        schema: ({ object, string }: any) => object.keys({
            name: string,
            description: string,
            category: string.optional(),
        })
    })

Link where you can find the playground with the main idea

您通常不需要手动输入回调函数参数,但在这种情况下,您有很多东西在这里输入为 any,这是不应该的。

如果您输入 schema 正确,一切似乎都运行良好。

我根本不知道 Joi,但我从您的示例中为 schema 函数派生了以下类型:

type SchemaFn = (
    types: ReturnType<typeof Joi['types']>,
    joi: typeof Joi
) => Joi.ObjectSchema<any>

然后你可以像这样使用:

function endpoint({ schema }: { schema: SchemaFn, path?: string }) {
  //...
}

因此,此代码没有类型错误。

class Test {
    @endpoint({
        schema: ({ object, string }) => object.keys({
            a: string.max(10),
            b: string.optional(),
        })
    })
    testMe() {
        return {
            type: `Cool`,
            message: `Ok`,
            code: 200,
        }

    }
}

甚至比没有错误更好的是,这里的 objectstring 是强类型的。因此,您可以对这些值的使用情况进行智能感知和类型检查。

Playground