[英]How to merge two classes in separate files into one ES6 module using TypeScript?
[英]Access a function in a separate module using typescript
我正在將一個 Nodejs 項目從 JavaScript 遷移到 TypeScript,並且我不斷從 JavaScript 之前運行的代碼中收到此錯誤。我在一個單獨的模塊中定義了一些函數,我想根據arguments 傳給了 function。
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
function 像這樣調用傳遞: validate('UserSchemas', 'signin')
,我想取回signin
function。 運行代碼時出現此錯誤:
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]
將拋出錯誤/返回未定義。
避免這種情況的正確方法是文字(或枚舉)的並集,或者 generics:
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.
}
雖然,如果這個 function 以任何方式使用用戶提供的數據,請在使用它之前對可能的路徑進行硬編碼或徹底驗證輸入,因為這只是一種編譯時措施,不能保護您免受用戶輸入無效信息和崩潰您的應用程序.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.