- Learn React with TypeScript 3
- Carl Rippon
- 371字
- 2021-06-10 19:16:44
Setting up an example
In order to explore this, we are going to work through an example of a TypeScript project referencing another project in Visual Studio Code:
- Firstly, let's create a new folder called Shared. This is going to be the project for shared code that could potentially be used in many other projects.
- In our Shared folder, let's create the following tsconfig.json as a starting point:
{
"compilerOptions": {
"target": "es5",
"outDir": "dist",
"module": "es6",
"sourceMap": true,
"noImplicitReturns": true,
"noImplicitAny": true,
"rootDir": "src"
},
"include": ["src/**/*"]
}
- Let's create an src folder containing a TypeScript file called utils.ts with the following function, randomString:
export function randomString() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16);
}
This is a function that creates a random string of characters, as the name suggests. We are going to use this function in another project.
- Let's start to create our second project now, so go back up to the root of our solution, and create a folder called ProjectA.
- Inside ProjectA, let's create the following tsconfig.json as a starting point:
{
"compilerOptions": {
"target": "es5",
"outDir": "dist",
"module": "es6",
"sourceMap": true,
"noImplicitReturns": true,
"noImplicitAny": true
},
"include": ["src/**/*"]
}
- Let's also create a folder called src in ProjectA, containing a TypeScript file called person.ts, with the following code:
import { randomString } from "../../Shared/dist/utils";
class Person {
id: string;
name: string;
constructor() {
this.id = randomString();
}
}
The code defines a simple class of information about a person. The unique identifier of the person is set to a random string in the constructor using the randomString function from our Shared project.
- Let's open up the terminal, go to our Shared folder, and compile our Shared project:
cd Shared
tsc
The Shared project compiles just fine.
- Let's try to compile ProjectA now:
cd ..
cd ProjectA
tsc
We get a compilation error:
error TS7016: Could not find a declaration file for module '../../Shared/dist/utils'. '.../Shared/dist/utils.js' implicitly has an 'any' type.
So, we created two dependent projects, but they don't properly understand each other yet, which is why we are getting the error. We'll resolve this in the following sections, using TypeScript 3's new features for multiple projects.
- Node.js+Webpack開發(fā)實戰(zhàn)
- 深度學習經(jīng)典案例解析:基于MATLAB
- Functional Programming in JavaScript
- UI智能化與前端智能化:工程技術(shù)、實現(xiàn)方法與編程思想
- Java:Data Science Made Easy
- Quarkus實踐指南:構(gòu)建新一代的Kubernetes原生Java微服務(wù)
- Hands-On Swift 5 Microservices Development
- Learning Python by Building Games
- 青少年信息學競賽
- Kotlin開發(fā)教程(全2冊)
- 深度探索Go語言:對象模型與runtime的原理特性及應(yīng)用
- Getting Started with Python
- C編程技巧:117個問題解決方案示例
- Vue.js光速入門及企業(yè)項目開發(fā)實戰(zhàn)
- Python應(yīng)用開發(fā)技術(shù)