【发布时间】:2019-02-09 10:13:03
【问题描述】:
我想运行一个包含 package.json、typescript 和 html 文件的空白 typescript 项目。- 类似于 Stackblitz blank-typescript project。 任何人都可以为我提供一步一步的指导,如何设置这样的项目。如果知道这一点很重要,我目前正在使用 Webstorm 作为 IDE。
提前谢谢你!
【问题讨论】:
标签: node.js html typescript npm
我想运行一个包含 package.json、typescript 和 html 文件的空白 typescript 项目。- 类似于 Stackblitz blank-typescript project。 任何人都可以为我提供一步一步的指导,如何设置这样的项目。如果知道这一点很重要,我目前正在使用 Webstorm 作为 IDE。
提前谢谢你!
【问题讨论】:
标签: node.js html typescript npm
我想我有我的解决方案。
使用npm install typescript --save在您的项目上安装打字稿
创建一个 tsconfig 文件以使用 tsc --init 为您的项目应用 typescript 规则
创建一个 index.ts 和 index.html 文件
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Promises vs. Observables</title>
</head>
<body>
<div id="app">
<script src="index.js"></script>
</div>
</body>
</html>
index.ts:
const world = '?️';
const appDiv: HTMLElement | null = document.getElementById('app');
if (appDiv) {
appDiv.innerHTML = `<h1>Hello ${world}</h1>`;
console.log(`hello ${world}`);
}
使用tsc -w在监视模式下编译
项目正在运行!如果我的解决方案可以做得更好,请随时告诉我!
【讨论】:
null 添加到您的 appDiv 声明中。大多数类型(包括HTMLElement)已经可以包含值 null。通过编译 const appDiv: HTMLElement = null; 向自己证明这一点。该联合声明的意思是 appDiv 可以包含 type <HTMLElement> 或 type <null>,这并不是您想要的。虽然可以说差异只是语义上的,但 typescript 是关于语义的。
strict: true 设置的。把它变成false之后,我就不需要添加null作为类型了。