使用typescript访问单独模块中的函数



我正在将一个Nodejs项目从JavaScript迁移到TypeScript,我一直从早期在JavaScript中工作的代码中得到这个错误。我在一个单独的模块中定义了一些函数,我想根据传递给函数的参数从另一个模块中的函数访问这个函数。

schemas/users.ts

export const signup = () => {}
export const signin = () => {}

schemas/index.ts

import * as UserSchemas from './users';
export { UserSchemas }

validate.ts

import * as schemas from './schemas';
const validate = (schemaCollection: string, schemaName: string) => {
const schemaFunc = schemas[schemaCollection][schemaName];
// Use the schemaFunc in the code following this line.
}

如果传递validate函数时调用如下:validate('UserSchemas', 'signin'),我想取回signin函数。当我运行代码时,我得到了这个错误:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof import("...schemas/index")'.
No index signature with a parameter of type 'string' was found on type 'typeof import("...schemas/index")'. ts(7053)

错误基本上是说您对validate的键入过于宽松,例如validate("Does", "not exist")是有效的,但schemas[schemaCollection][schemaName]会抛出一个错误/返回未定义。

避免这种情况的正确方法要么是文本(或枚举(的联合,要么是泛型:

const validate = <T extends keyof typeof schemas, K extends keyof typeof schemas[T]>(schemaCollection: T, schemaName: K) => {
const schemaFunc = schemas[schemaCollection][schemaName];
// Use the schemaFunc in the code following this line.
}

游乐场

尽管,如果此函数以任何方式使用用户提供的数据,请在使用之前对可能的路径进行硬编码或彻底验证输入,因为这只是一种编译时度量,不能保护您免受用户输入无效信息和使应用程序崩溃的影响。

最新更新