【发布时间】:2019-01-01 20:19:26
【问题描述】:
我正在使用没有types 声明文件的第三个库。所以我需要在我的项目中添加库的类型。
但我试了很多次,结果总是错误。
这是我的tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
"esModuleInterop": true,
"module": "commonjs",
"moduleResolution": "node",
"removeComments": true,
"sourceMap": true,
"target": "esnext",
"types": ["node"],
"strict": true,
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/node_modules/*", "**/*.spec.ts"]
}
我在我的根项目中创建了一个global.d.ts 文件并声明了模块:
declare module 'matrix-js-sdk' {
interface Promise {
done(callback: () => void): void
}
interface Client {
joinRoom(roomId: string): Promise
}
export function createClient(options: {
baseUrl: string
accessToken: string
userId: string
}): Client
}
导入第三个库:
import sdk from 'matrix-js-sdk'
// error: Cann't find the declaration file for the module 'matrix-js-sdk'
另外,我还尝试创建root/src/@types/matrix-js-sdk/index.d.ts文件并写声明:
interface Promise {
done(callback: () => void): void
}
interface Client {
joinRoom(roomId: string): Promise
}
export function createClient(options: {
baseUrl: string
accessToken: string
userId: string
}): Client
但它永远不会起作用。
==================已更新====================
现在我可以在src/global.d.ts(不是根项目)中编写声明,并将其引用到编译中:
/// <reference path="../global.d.ts" />
import sdk from 'matrix-js-sdk'
但不推荐reference语法,我尝试在tsconfig.json的files字段中包含src/global.d.ts:
"files": ["src/global.d.ts"],
"include": ["src/**/*"],
"exclude": ["node_modules", "**/node_modules/*", "**/*.spec.ts"]
它再次抛出同样的错误:
Could not find a declaration file for module 'matrix-js-sdk'
另一个,src/@types/matrix-js-sdk/index.d.ts 还是不行(我更喜欢用这种方式)。
【问题讨论】:
标签: typescript type-declaration