我正在学习TypeScript,现在正在与淘汰赛类型作斗争。
现在,我导入依赖项,然后像下面这样在我的showPdf.ts
文件中使用它们:
import $ = require("jquery");
import ko = require("knockout");
import pdfjsLib = require("pdfjs-dist/build/pdf");
export class PdfViewModel {
pdfUrl: any;
constructor(initUrl: string) {
this.pdfUrl = ko.observable(initUrl);
}
var loadingTask = pdfjsLib.getDocument(url);
loadingTask.promise.then((pdf: any) => {
pdf.getPage(1).then((page: any) => {
...
}
}
...
}
现在,我想将pdfUrl
的类型设置为KnockoutObservable<string>
。在不进行任何其他更改的情况下,我现在得到了一个翻译错误:
Error TS2403: Build:Subsequent variable declarations must have the same type. Variable 'ko' must be of type 'typeof import("C:/Users/BluE/Source/Repos/ShowPdfTest/node_modules/knockout/build/types/knockout")', but here has type 'KnockoutStatic'. (1060, 13)
我通过将敲除导入更改为此来解决此问题:
/// <reference path="../TypeScript/@types/knockout/index.d.ts" />
import $ = require("jquery");
import pdfjsLib = require("pdfjs-dist/build/pdf
现在我已经读过,使用这样的引用实际上是不好的做法。那么正确的方法是什么?
Visual Studio还突出显示了2个问题,尽管它们可以编译和正常工作。
Import 'pdfjsLib' is never used
Symbol 'pdfjsLib' cannot be properly resolved, probably it is located in inaccessible module
如果删除导入,则另一行将不再透明。
Error TS2304: Build:Cannot find name 'pdfjsLib'.
我在这里做错什么了吗?如果是这样,正确的做法是什么?
tsconfig.json
:
{
"compileOnSave": true,
"compilerOptions": {
"strict": false,
"noEmitOnError": true,
"sourceMap": true,
"removeComments": false,
"target": "es5",
"outDir": "wwwroot/js/",
"module": "amd",
"moduleResolution": "node",
"lib": [
"es5",
"dom"
],
"typeRoots": []
},
"exclude": [
"node_modules",
"wwwroot"
]
}
package.json
:
{
"version": "0.5.0",
"name": "showpdf.test",
"private": true,
"devDependencies": {
"@types/jquery": "3.3.30",
"@types/knockout": "3.4.66",
"@types/pdfjs-dist": "2.0.0"
},
"dependencies": {
"requirejs": "2.3.6",
"jquery": "3.4.1",
"knockout": "3.5.0",
"pdfjs-dist": "2.0.943"
}
}
*.cshtml
中有效的html部分:(如果相关,我正在使用ASP.Net Core 2.2。)
<script src="~/lib/requirejs/dist/require.js"></script>
<script>
require.config({
baseUrl: "/",
paths: {
"jquery": "lib/jquery/dist/jquery-3.4.1",
"knockout": "lib/knockout/dist/knockout-3.5.0",
"pdfjs-dist/build/pdf": "lib/pdfjs/dist/build/pdf",
'pdfjs-dist/build/pdf.worker': "lib/pdfjs/dist/build/pdf.worker",
"showpdf-test": "js/showpdf"
},
waitSeconds: 15
});
require(
["knockout", "showpdf-test"],
function (ko, showpdf) {
var viewModel = new showpdf.PdfViewModel("");
ko.applyBindings(viewModel);
}
);
</script>
我只是注意到我正在使用Nuget软件包的tickoutjs。我怀疑我是否真的需要它。 nuget包有什么已知问题吗?
答案 0 :(得分:0)
我不完全确定它会起作用,但是尝试改用import * as ko from 'knockout
并删除lib
和typeRoots
。如果这样不起作用,请尝试使用此tsconfig文件并将文件重命名为tsconfig.json
:
{
"compilerOptions": {
"module": "amd",
"target": "es6",
"moduleResolution": "node"
},
"exclude": [
"node_modules",
"wwwroot"
]
}