From 0d8b26fdabe47936fa408968584a184870b20e9d Mon Sep 17 00:00:00 2001 From: Augustin Mauroy Date: Mon, 16 Sep 2024 14:09:38 +0200 Subject: [PATCH] content(learn): update resources about typescript (#6951) * content(learn): update ressources about typescript * adding important note * content(learn): update from feedback Co-Authored-By: Antoine du Hamel * content(learn): remove global install of tsc * fix fails from github copilot fix fails from github copilot * fix: remove old stuff from navigation * update * update * Update from feedback Co-Authored-By: Brian Muenzenmeyer --------- Co-authored-by: Antoine du Hamel Co-authored-by: Brian Muenzenmeyer --- apps/site/navigation.json | 25 ++- .../getting-started/nodejs-with-typescript.md | 185 ------------------ .../pages/en/learn/typescript/introduction.md | 50 +++++ .../pages/en/learn/typescript/run-natively.md | 38 ++++ apps/site/pages/en/learn/typescript/run.md | 49 +++++ .../pages/en/learn/typescript/transpile.md | 118 +++++++++++ apps/site/redirects.json | 4 + apps/site/site.json | 10 +- packages/i18n/locales/en.json | 10 +- 9 files changed, 294 insertions(+), 195 deletions(-) delete mode 100644 apps/site/pages/en/learn/getting-started/nodejs-with-typescript.md create mode 100644 apps/site/pages/en/learn/typescript/introduction.md create mode 100644 apps/site/pages/en/learn/typescript/run-natively.md create mode 100644 apps/site/pages/en/learn/typescript/run.md create mode 100644 apps/site/pages/en/learn/typescript/transpile.md diff --git a/apps/site/navigation.json b/apps/site/navigation.json index 430d40fbbb90..f1691a6e868c 100644 --- a/apps/site/navigation.json +++ b/apps/site/navigation.json @@ -167,10 +167,6 @@ "link": "/learn/getting-started/nodejs-the-difference-between-development-and-production", "label": "components.navigation.learn.gettingStarted.links.nodejsTheDifferenceBetweenDevelopmentAndProduction" }, - "nodejsWithTypescript": { - "link": "/learn/getting-started/nodejs-with-typescript", - "label": "components.navigation.learn.gettingStarted.links.nodejsWithTypescript" - }, "nodejsWithWebassembly": { "link": "/learn/getting-started/nodejs-with-webassembly", "label": "components.navigation.learn.gettingStarted.links.nodejsWithWebassembly" @@ -189,6 +185,27 @@ } } }, + "typescript": { + "label": "components.navigation.learn.typescript.links.typescript", + "items": { + "introduction": { + "link": "/learn/typescript/introduction", + "label": "components.navigation.learn.typescript.links.introduction" + }, + "transpile": { + "link": "/learn/typescript/transpile", + "label": "components.navigation.learn.typescript.links.transpile" + }, + "run": { + "link": "/learn/typescript/run", + "label": "components.navigation.learn.typescript.links.run" + }, + "runNatively": { + "link": "/learn/typescript/run-natively", + "label": "components.navigation.learn.typescript.links.runNatively" + } + } + }, "asynchronousWork": { "label": "components.navigation.learn.asynchronousWork.links.asynchronousWork", "items": { diff --git a/apps/site/pages/en/learn/getting-started/nodejs-with-typescript.md b/apps/site/pages/en/learn/getting-started/nodejs-with-typescript.md deleted file mode 100644 index a254dca66906..000000000000 --- a/apps/site/pages/en/learn/getting-started/nodejs-with-typescript.md +++ /dev/null @@ -1,185 +0,0 @@ ---- -title: Node.js with TypeScript -layout: learn -authors: sbielenica, ovflowd, vaishnav-mk, AugustinMauroy ---- - -# Node.js with TypeScript - -## What is TypeScript - -**[TypeScript](https://www.typescriptlang.org)** is an open-source language maintained and developed by Microsoft. It's loved and used by a lot of software developers around the world. - -Basically, it's a superset of JavaScript that adds new capabilities to the language. The most notable addition is static type definitions, something that is not present in plain JavaScript. Thanks to types, it's possible, for example, to declare what kind of arguments we are expecting and what is returned exactly in our functions or what's the exact shape of the object that we are creating. TypeScript is a really powerful tool and opens a new world of possibilities in JavaScript projects. It makes our code more secure and robust by preventing many bugs before the code is even shipped - it catches problems during code development and integrates wonderfully with code editors like Visual Studio Code. - -We can talk about other TypeScript benefits later, let's see some examples now! - -### Examples - -Take a look at this code snippet and then we can unpack it together: - -```ts -type User = { - name: string; - age: number; -}; - -function isAdult(user: User): boolean { - return user.age >= 18; -} - -const justine: User = { - name: 'Justine', - age: 23, -}; - -const isJustineAnAdult: boolean = isAdult(justine); -``` - -The first part (with the `type` keyword) is responsible for declaring our custom object type representing users. Later we utilize this newly created type to create function `isAdult` that accepts one argument of type `User` and returns `boolean`. After this, we create `justine`, our example data that can be used for calling the previously defined function. Finally, we create a new variable with information on whether `justine` is an adult. - -There are additional things about this example that you should know. Firstly, if we would not comply with declared types, TypeScript would alarm us that something is wrong and prevent misuse. Secondly, not everything must be typed explicitly - TypeScript is very smart and can deduce types for us. For example, variable `isJustineAnAdult` would be of type `boolean` even if we didn't type it explicitly or `justine` would be valid argument for our function even if we didn't declare this variable as of `User` type. - -Okay, so we have some TypeScript code. Now how do we run it? - -**First thing to do is to install TypeScript in our project:** - -```bash -npm i -D typescript -``` - -Now we can compile it to JavaScript using `tsc` command in the terminal. Let's do it! - -**Assuming that our file is named `example.ts`, the command would look like:** - -```bash -npx tsc example.ts -``` - -> [npx](https://www.npmjs.com/package/npx) here stands for Node Package Execute. This tool allows us to run TypeScript's compiler without installing it globally. - -`tsc` is the TypeScript compiler which will take our TypeScript code and compile it to JavaScript. -This command will result in a new file named `example.js` that we can run using Node.js. -Now when we know how to compile and run TypeScript code let's see TypeScript bug-preventing capabilities in action! - -**This is how we will modify our code:** - -```ts -type User = { - name: string; - age: number; -}; - -function isAdult(user: User): boolean { - return user.age >= 18; -} - -const justine: User = { - name: 'Justine', - age: 'Secret!', -}; - -const isJustineAnAdult: string = isAdult(justine, "I shouldn't be here!"); -``` - -**And this is what TypeScript has to say about this:** - -```console -example.ts:12:5 - error TS2322: Type 'string' is not assignable to type 'number'. - -12 age: 'Secret!', - ~~~ - - example.ts:3:5 - 3 age: number; - ~~~ - The expected type comes from property 'age' which is declared here on type 'User' - -example.ts:15:7 - error TS2322: Type 'boolean' is not assignable to type 'string'. - -15 const isJustineAnAdult: string = isAdult(justine, "I shouldn't be here!"); - ~~~~~~~~~~~~~~~~ - -example.ts:15:51 - error TS2554: Expected 1 arguments, but got 2. - -15 const isJustineAnAdult: string = isAdult(justine, "I shouldn't be here!"); - ~~~~~~~~~~~~~~~~~~~~~~ - - -Found 3 errors in the same file, starting at: example.ts:12 -``` - -As you can see TypeScript successfully prevents us from shipping code that could work unexpectedly. That's wonderful! - -## More about TypeScript - -TypeScript offers a whole lot of other great mechanisms like interfaces, classes, utility types and so on. Also, on bigger projects you can declare your TypeScript compiler configuration in a separate file and granularly adjust how it works, how strict it is and where it stores compiled files for example. You can read more about all this awesome stuff in [the official TypeScript docs](https://www.typescriptlang.org/docs). - -Some of the other benefits of TypeScript that are worth mentioning are that it can be adopted progressively, it helps making code more readable and understandable and it allows developers to use modern language features while shipping code for older Node.js versions. - -## Running TypeScript Code in Node.js - -Node.js cannot run TypeScript natively. You cannot call `node example.ts` from the command line directly. But there are three solutions to this problem: - -### Compiling TypeScript to JavaScript - -If you want to run TypeScript code in Node.js, you need to compile it to JavaScript first. You can do this using the TypeScript compiler `tsc` as shown earlier. - -Here's a small example: - -```bash -npx tsc example.ts -node example.js -``` - -### Running TypeScript Code with `ts-node` - -You can use [ts-node](https://typestrong.org/ts-node/) to run TypeScript code directly in Node.js without the need to compile it first. But it's not typechecking your code. So we recommend to type check your code first with `tsc` and then run it with `ts-node` before shipping it. - -To use `ts-node`, you need to install it first: - -```bash -npm i -D ts-node -``` - -Then you can run your TypeScript code like this: - -```bash -npx ts-node example.ts -``` - -### Running TypeScript Code with `tsx` - -You can use [tsx](https://tsx.is/) to run TypeScript code directly in Node.js without the need to compile it first. But it's not typechecking your code. So we recommend to type check your code first with `tsc` and then run it with `tsx` before shipping it. - -To use `tsx`, you need to install it first: - -```bash -npm i -D tsx -``` - -Then you can run your TypeScript code like this: - -```bash -npx tsx example.ts -``` - -If you want to use `tsx` via `node`, you can register `tsx` via `--import`: - -```bash -node --import=tsx example.ts -``` - -## TypeScript in the Node.js world - -TypeScript is well-established in the Node.js world and used by many companies, open-source projects, tools and frameworks. -Some of the notable examples of open-source projects using TypeScript are: - -- [NestJS](https://nestjs.com/) - robust and fully-featured framework that makes creating scalable and well-architected systems easy and pleasant -- [TypeORM](https://typeorm.io/#/) - great ORM influenced by other well-known tools from other languages like Hibernate, Doctrine or Entity Framework -- [Prisma](https://prisma.io/) - next-generation ORM featuring a declarative data model, generated migrations and fully type-safe database queries -- [RxJS](https://rxjs.dev/) - widely used library for reactive programming -- [AdonisJS](https://adonisjs.com) - A fully featured web framework with Node.js -- [FoalTs](https://foalts.org/) - The Elegant Nodejs Framework - -And many, many more great projects... Maybe even your next one! diff --git a/apps/site/pages/en/learn/typescript/introduction.md b/apps/site/pages/en/learn/typescript/introduction.md new file mode 100644 index 000000000000..4cd976f2fb58 --- /dev/null +++ b/apps/site/pages/en/learn/typescript/introduction.md @@ -0,0 +1,50 @@ +--- +title: Introduction to TypeScript +layout: learn +authors: sbielenica, ovflowd, vaishnav-mk, AugustinMauroy +--- + +# Introduction to TypeScript + +## What is TypeScript + +**[TypeScript](https://www.typescriptlang.org)** is an open-source language maintained and developed by Microsoft. + +Basically, TypeScript adds additional syntax to JavaScript to support a tighter integration with your editor. Catch errors early in your editor or in your CI/CD pipeline, and write more maintainable code. + +We can talk about other TypeScript benefits later, let's see some examples now! + +## First TypeScript code + +Take a look at this code snippet and then we can unpack it together: + + + +```ts +type User = { + name: string; + age: number; +}; + +function isAdult(user: User): boolean { + return user.age >= 18; +} + +const justine = { + name: 'Justine', + age: 23, +} satisfies User; + +const isJustineAnAdult = isAdult(justine); +``` + +The first part (with the `type` keyword) is responsible for declaring our custom object type representing users. Later we utilize this newly created type to create function `isAdult` that accepts one argument of type `User` and returns `boolean`. After this, we create `justine`, our example data that can be used for calling the previously defined function. Finally, we create a new variable with information on whether `justine` is an adult. + +There are additional things about this example that you should know. Firstly, if we do not comply with the declared types, TypeScript will inform us that something is wrong and prevent misuse. Secondly, not everything must be typed explicitly—TypeScript infers types for us. For example, the variable `isJustineAnAdult` is of type `boolean` even if we didn't type it explicitly, and `justine` would be a valid argument for our function even though we didn't declare this variable as of `User` type. + +## How to run TypeScript code + +Okay, so we have some TypeScript code. Now how do we run it? +There are few possible ways to run TypeScript code, we will cover all of them in the next articles. diff --git a/apps/site/pages/en/learn/typescript/run-natively.md b/apps/site/pages/en/learn/typescript/run-natively.md new file mode 100644 index 000000000000..6a101ad17601 --- /dev/null +++ b/apps/site/pages/en/learn/typescript/run-natively.md @@ -0,0 +1,38 @@ +--- +title: Running TypeScript Natively +layout: learn +authors: AugustinMauroy +--- + +> **⚠️WARNING⚠️:** All content in this article uses Node.js experimental features. Please make sure you are using a version of Node.js that supports the features mentioned in this article. And remember that experimental features can change in future versions of Node.js. + +# Running TypeScript Natively + +In the previous articles, we learned how to run TypeScript code using transpilation and with a runner. In this article, we will learn how to run TypeScript code using Node.js itself. + +## Running TypeScript code with Node.js + +Since V22.6.0, Node.js has experimental support for some TypeScript syntax. You can write code that's valid TypeScript directly in Node.js without the need to transpile it first. + +So how do you run TypeScript code with Node.js? + +```bash +node --experimental-strip-types example.ts +``` + +The `--experimental-strip-types` flag tells Node.js to strip the type annotations from the TypeScript code before running it. + +And that's it! You can now run TypeScript code directly in Node.js without the need to transpile it first, and use TypeScript to catch type-related errors. +Future versions of Node.js will include support for TypeScript without the need for a command line flag. + +## Limitations + +At the time of writing, the experimental support for TypeScript in Node.js has some limitations. To allow TypeScript to run in node.js, our collaborators have chosen to only strip types from the code. + +You can get more information on the [API docs](https://nodejs.org/docs/latest/api/typescript.html#unsupported-typescript-features) + +## Important notes + +Thanks to all the contributors who have made this feature possible. We hope that this feature will be stable and available in the LTS version of Node.js soon. + +We can understand that this feature is experimental and has some limitations; if that doesn't suit your use-case, please use something else, or contribute a fix. Bug reports are also welcome, please keep in mind the project is run by volunteers, without warranty of any kind, so please be patient if you can't contribute the fix yourself. diff --git a/apps/site/pages/en/learn/typescript/run.md b/apps/site/pages/en/learn/typescript/run.md new file mode 100644 index 000000000000..b3404b1c4556 --- /dev/null +++ b/apps/site/pages/en/learn/typescript/run.md @@ -0,0 +1,49 @@ +--- +title: Running TypeScript with a runner +layout: learn +authors: AugustinMauroy +--- + +# Running TypeScript with a runner + +In the previous article, we learned how to run TypeScript code using transpilation. In this article, we will learn how to run TypeScript code using a runner. + +## Running TypeScript code with `ts-node` + +[ts-node](https://typestrong.org/ts-node/) is a TypeScript execution environment for Node.js. It allows you to run TypeScript code directly in Node.js without the need to compile it first. Note, however, that it does not type check your code. So we recommend to type check your code first with `tsc` and then run it with `ts-node` before shipping it. + +To use `ts-node`, you need to install it first: + +```bash +npm i -D ts-node +``` + +Then you can run your TypeScript code like this: + +```bash +npx ts-node example.ts +``` + +## Running TypeScript code with `tsx` + +[tsx](https://tsx.is/) is another TypeScript execution environment for Node.js. It allows you to run TypeScript code directly in Node.js without the need to compile it first. Note, however, that it does not type check your code. So we recommend to type check your code first with `tsc` and then run it with `tsx` before shipping it. + +To use `tsx`, you need to install it first: + +```bash +npm i -D tsx +``` + +Then you can run your TypeScript code like this: + +```bash +npx tsx example.ts +``` + +### Registering `tsx` via `node` + +If you want to use `tsx` via `node`, you can register `tsx` via `--import`: + +```bash +node --import=tsx example.ts +``` diff --git a/apps/site/pages/en/learn/typescript/transpile.md b/apps/site/pages/en/learn/typescript/transpile.md new file mode 100644 index 000000000000..62c042d4e902 --- /dev/null +++ b/apps/site/pages/en/learn/typescript/transpile.md @@ -0,0 +1,118 @@ +--- +title: Running TypeScript code using transpilation +layout: learn +authors: AugustinMauroy +--- + +# Running TypeScript code using transpilation + +Transpilation is the process of converting source code from one language to another. In the case of TypeScript, it's the process of converting TypeScript code to JavaScript code. This is necessary because browsers and Node.js can't run TypeScript code directly. + +## Compiling TypeScript to JavaScript + +The most common way to run TypeScript code is to compile it to JavaScript first. You can do this using the TypeScript compiler `tsc`. + +**Step 1:** Write your TypeScript code in a file, for example `example.ts`. + + + +```ts +type User = { + name: string; + age: number; +}; + +function isAdult(user: User): boolean { + return user.age >= 18; +} + +const justine = { + name: 'Justine', + age: 23, +} satisfies User; + +const isJustineAnAdult = isAdult(justine); +``` + +**Step 2:** Install TypeScript locally using a package manager: + +In this example we're going to use npm, you can check our [our introduction to the npm package manager](/learn/getting-started/an-introduction-to-the-npm-package-manager) for more information. + +```bash displayName="Install TypeScript locally" +npm i -D typescript # -D is a shorthand for --save-dev +``` + +**Step 3:** Compile your TypeScript code to JavaScript using the `tsc` command: + +```bash +npx tsc example.ts +``` + +> **NOTE:** `npx` is a tool that allows you to run Node.js packages without installing them globally. + +`tsc` is the TypeScript compiler which will take our TypeScript code and compile it to JavaScript. +This command will result in a new file named `example.js` that we can run using Node.js. +Now when we know how to compile and run TypeScript code let's see TypeScript bug-preventing capabilities in action! + +**Step 4:** Run your JavaScript code using Node.js: + +```bash +node example.js +``` + +You should see the output of your TypeScript code in the terminal + +## If there are type errors + +If you have type errors in your TypeScript code, the TypeScript compiler will catch them and prevent you from running the code. For example, if you change the `age` property of `justine` to a string, TypeScript will throw an error: + +We will modify our code like this, to voluntarily introduce a type error: + +```ts +type User = { + name: string; + age: number; +}; + +function isAdult(user: User): boolean { + return user.age >= 18; +} + +const justine: User = { + name: 'Justine', + age: 'Secret!', +}; + +const isJustineAnAdult: string = isAdult(justine, "I shouldn't be here!"); +``` + +And this is what TypeScript has to say about this: + +```console +example.ts:12:5 - error TS2322: Type 'string' is not assignable to type 'number'. + +12 age: 'Secret!', + ~~~ + + example.ts:3:5 + 3 age: number; + ~~~ + The expected type comes from property 'age' which is declared here on type 'User' + +example.ts:15:7 - error TS2322: Type 'boolean' is not assignable to type 'string'. + +15 const isJustineAnAdult: string = isAdult(justine, "I shouldn't be here!"); + ~~~~~~~~~~~~~~~~ + +example.ts:15:51 - error TS2554: Expected 1 arguments, but got 2. + +15 const isJustineAnAdult: string = isAdult(justine, "I shouldn't be here!"); + ~~~~~~~~~~~~~~~~~~~~~~ + + +Found 3 errors in the same file, starting at: example.ts:12 +``` + +As you can see, TypeScript is very helpful in catching bugs before they even happen. This is one of the reasons why TypeScript is so popular among developers. diff --git a/apps/site/redirects.json b/apps/site/redirects.json index 8b3b370b76ae..32d1e794e898 100644 --- a/apps/site/redirects.json +++ b/apps/site/redirects.json @@ -287,6 +287,10 @@ { "source": "/:locale/download/current", "destination": "/:locale/download/package-manager/current" + }, + { + "source": "/:locale/learn/getting-started/nodejs-with-typescript", + "destination": "/:locale/learn/typescript/introduction" } ], "internal": [] diff --git a/apps/site/site.json b/apps/site/site.json index 338cc997df7d..8613581d70fa 100644 --- a/apps/site/site.json +++ b/apps/site/site.json @@ -37,12 +37,12 @@ }, "websiteBadges": { "index": { - "startDate": "2024-04-24T00:00:00.000Z", - "endDate": "2024-05-24T00:00:00.000Z", + "startDate": "2024-09-01T00:00:00.000Z", + "endDate": "2024-10-01T00:00:00.000Z", "kind": "default", - "title": "Survey", - "text": "Help us shape the next 10 years of Node.js", - "link": "https://linuxfoundation.surveymonkey.com/r/nodenext10survey24" + "title": "Discover", + "text": "TypeScript in Node.js", + "link": "https://nodejs.org/en/learn/typescript/introduction/" } } } diff --git a/packages/i18n/locales/en.json b/packages/i18n/locales/en.json index 4b6c604270b6..c96493c36e68 100644 --- a/packages/i18n/locales/en.json +++ b/packages/i18n/locales/en.json @@ -36,13 +36,21 @@ "anIntroductionToTheNpmPackageManager": "An introduction to the npm package manager", "ecmascript2015Es6AndBeyond": "ECMAScript 2015 (ES6) and beyond", "nodejsTheDifferenceBetweenDevelopmentAndProduction": "Node.js, the difference between development and production", - "nodejsWithTypescript": "Node.js with TypeScript", "nodejsWithWebassembly": "Node.js with WebAssembly", "debugging": "Debugging Node.js", "profiling": "Profiling Node.js Applications", "securityBestPractices": "Security Best Practices" } }, + "typescript": { + "links": { + "typescript": "TypeScript", + "introduction": "Introduction to TypeScript", + "transpile": "Running TypeScript code using transpilation", + "run": "Running TypeScript with a runner", + "runNatively": "Running TypeScript Natively" + } + }, "asynchronousWork": { "links": { "asynchronousWork": "Asynchronous Work",