typescript

NEW: Built-in TypeScript support in Node.js – Finally

Exciting news today as native TypeScript support finally comes to Node.js!

Yes you can now use types natively in Node.js.

So throw typescript and ts-node in the garbage.

❌Before now:

Node.js only ever cared for JavaScript files.

This would never have run:

Try it and you’d get this unpleasant error:

Our best bet was to install TypeScript and compile with tsc.

And millions of developers agreed it was a pretty good option:

But this was painful — having to install the same old package and type out the same command over and over again.

Extra compilation step to JS and having to deal with TypeScript configurations and stuff.

Pretty frustrating — especially when we’re just doing a bit of testing.

That was why ts-node arrived to try to save the day — but it still wasn’t enough.

We could now run the TypeScript files directly:

We could even start an interactive session on the fly like we’d do with the standalone node command:

And everyone loved it:

But it was still an extra dependency, and we still had to install typescript.

We still had more subtle intricacies to be aware of, like how to use ts-node for ES modules with the --esm flag:

✅Now:

All this changes now with all the brand-new upgrades now in Node:

  • Native built-in TypeScript support.
  • Zero dependencies
  • Zero intermediate files and module configurations

Now all our favorite JS tools like Prettier, Next.js, and Webpack can have safer and intellisense-friendly config files.

Okay almost no one has Webpack in their favorite tools list but still…

Look we already have pull requests like this to support prettier.config.ts in Prettier — and they’re going to be taking big steps forward thanks to this new development.

How does it work behind the scenes?

Support for TypeScript will be gradual, so right now it only supports types — you can’t use more TypeScript-y features like enums (although who uses enums these days).

It uses the @swc/wasm-typescript tool to internally strip the TypeScript file of all its types.

So this:

JavaScript
const url: string = 'codingbeautydev.com'; const capitalized: string = url.toUpperCase(); console.log(`Capitalized: ${capitalized}`);

Turns into this:

JavaScript
const url = 'codingbeautydev.com'; const capitalized = url.toUpperCase(); console.log(`Capitalized: ${capitalized}`);

How to start using TypeScript in Node.js

Early beginnings like I said, so it’s still experimental and for now you’ll need the --experimental-strip-types flag:

JavaScript
node --experimental-strip-types my-file

This will be in an upcoming release.

Final thoughts

Built-in TypeScript is a serious power move to make Node.js a much more enjoyable platform for JS devs. I’ll definitely be using this.

Even though the support is not yet as seamless as in Bun or Deno, it makes a far-reaching impact on the entire JavaScript ecosystem as Node is still the most popular JS backend framework by light years.

Next.js: How to set page title and meta description

Setting the page title and meta description helps improve search engine visibility, increase click-through rates, and provide concise summaries of webpage content.

In this article, we’re going to learn how we easily set the page title and meta description in a Next.js project.

In this article

Set static page title and meta description in Next.js App Router

To set page title and meta description statically in Next.js 13’s app directory, create a Metadata object in a page.tsx file and export it:

src/app/page.tsx
import React from 'react'; import { Metadata } from 'next'; export const metadata: Metadata = { title: 'Coding Beauty', description: 'wp.codingbeautydev.com: Coding - the art, the science, and the passion.', }; export default function Page() { return ( <main> <h1>Welcome to Coding Beauty</h1> </main> ); }

The tab will have this title, and the page will have a meta tag containing this description:

A Next.js page with a title and meta description.

We can also do this in a layout.tsx to make every page using this layout have this title and meta description by default – if the page doesn’t have its own.

src/app/layout.tsx
import { Metadata } from 'next'; import '@/styles/globals.css'; export const metadata: Metadata = { title: 'Coding Beauty', description: 'The official Coding Beauty home page.', icons: { icon: '/favicon.png', }, }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body>{children}</body> </html> ); }

Set title and meta description dynamically in Next.js App Router

You can use the generateMetadata() function to set the page title and meta description using dynamic information we don’t know beforehand, like data from an API.

TypeScript
export function generateMetadata({ params }: Props): Promise<Metadata> { // fetch data with `params` // return a `Metadata` object return { title: post.name, description: post.description, } }

Let’s look at a full example, where we fetch API data for a post in our hypothetical social media app, and we use generateMetadata() to set the page title and meta description for the page based on what we get from the endpoint URL.

src/pages/posts/[id]/page.tsx
import { Metadata } from 'next'; type Props = { params: { id: string }; }; export async function generateMetadata({ params, }: Props): Promise<Metadata> { const id = params.id; const url = `https://api.mysocialapp.com/posts/${id}`; const post = await fetch(url).then((res) => res.json()); return { title: post.title, description: post.description, }; } export default async function Page({ params }: Props) { const { id } = params; const url = `https://api.mysocialapp.com/posts/${id}`; // fetch again! // But don't worry, Next.js caches the `fetch()` calls const post = await fetch(url).then((res) => res.json()); return ( <> <h1>{post.title}</h1> <div>{post.content}</div> </> ); }

We fetch data from the same endpoint twice, one for the title and meta description, and another to display the title and other information to the actual users on the page.

Next.js caches the results of the fetch in generateMetadata() for use in Page to prevent multiple requests and avoid performance hits.

If you export a Metadata object and also have generateMetadata() function, Next.js will use generateMetadata()‘s return value.

Set page title and meta description in Next.js Pages Router (<= 12)

To set the page title and meta description in the Next.js pages directory, create a Head component, and place meta and title tags in it, like you would in vanilla HTML:

pages/index.tsx
import Head from 'next/head'; export default function Home() { return ( <> <Head> <title>Coding Beauty</title> <meta name="description" content="A brand all about coding passion and success" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.png" /> </Head> <main> <h1>Welcome to Coding Beauty</h1> </main> </> ); }

We can also set the page title and meta description in your _app.tsx or _app.jsx file to make each page without a title or description use this as a default.

pages/_app.tsx
import '@/styles/globals.css'; import type { AppProps } from 'next/app'; import Head from 'next/head'; export default function App({ Component, pageProps }: AppProps) { return ( <> <Head> <title>Coding Beauty</title> <meta name="description" content="A page on the Coding Beauty website" /> </Head> <Component {...pageProps} /> </> ); }

Set page title and meta description dynamically in Next.js Pages Router (<= 12)

You can also set the page title and meta description in the pages directory based on some data not known ahead of time.

For instance, to set the meta information based on API data, you’ll fetch the data in getServerSideProps and display it in the title and meta tags that are in the Head tag.

pages/[id].tsx
import { GetServerSideProps } from 'next'; import Head from 'next/head'; export const getServerSideProps: GetServerSideProps = async (context) => { const { params } = context; const { id } = params!; const result = await fetch(`api.mystore.com/books/${id}`); const { title, description, details } = await result.json(); return { props: { title, description, details, }, }; }; export default function Home(props: any) { const { title, description, details } = props; return ( <> <Head> {/* 👇 set page title and meta description dynamically */} <title>{title}</title> <meta name="description" content={description} /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.png" /> </Head> <main> <h1>{title}</h1> <p>{details}</p> </main> </> ); }

How to create a type from type or object keys or values in TypeScript

In this article

Create type from object keys in TypeScript

To create a type from an object’s keys in TypeScript, use the keyof typeof object. For example:

TypeScript
const brand = { name: 'Coding Beauty', domain: 'wp.codingbeautydev.com', color: 'blue', }; // 👇 type Keys = 'name' | 'domain' | 'color'; type BrandKeys = keyof typeof brand;

With this, you’ll have a type that only accepts strings matching the key name, and your code editor’s intellisense should indicate:

The new type only accepts values matching the object's keys.
The new type only accepts values matching the object’s keys.

Create type from another type’s keys in TypeScript

We use typeof because brand is an instance object, not a type. If it was a type, we would omit typeof:

TypeScript
type Brand = { name: string; domain: string; color: string; }; // 👇 type Keys = 'name' | 'domain' | 'color'; type BrandKeys = keyof Brand;

As before, you’ll have a type that only contains strings matching the key name, and your code editor should detect this:

The new type only accepts values matching the first type's keys.
The new type only accepts values matching the first type’s keys.

Create type from object values in TypeScript

We can use typeof and type indexing to easily create a type from an object’s values in TypeScript:

TypeScript
const site = { url: 'wp.codingbeautydev.com', color: 'blue', topic: 'coding', } as const; // 👈 const assertion // 👇 type Values = 'wp.codingbeautydev.com' | 'color' | 'coding' type Values = (typeof site)[keyof typeof site];

We this, we’ll have a type that only accepts strings matching the values of the object:

The new type only accepts values matching the object's values.
The new type only accepts values matching the object’s values.

Otherwise, there’ll be a TypeScript error

You can only values matching the object's values to the new type.

Create generic type from object values in TypeScript

The as const is called a const assertion in TypeScript. It tells the compiler to infer the most specific type possible from an expression. Without it, the inferred value type will be a primitive, like string or number or union of these primitives – string | number for example.

TypeScript
const site = { url: 'wp.codingbeautydev.com', color: 'blue', topic: 'coding', }; // 👇 type Values = 'string' type Values = (typeof site)[keyof typeof site]; // 👇 No error - `Values` takes any string const testObj: Values = 'random string';

Values is no different from the string type here, and VS Code confirms it:

The Values type is a string.
The Values type is a string.

If there are multiple primitive types, the resulting generic type will be a union of all those primitives:

TypeScript
const site = { url: 'wp.codingbeautydev.com', age: 1000, // 👈 also `number` type now topic: 'coding', }; // 👇 type Values = 'string' | number type Values = (typeof site)[keyof typeof site]; // 👇 No error const testObj: Values = 34124;
The Values type is a string | number type.
The Values type is a string | number type.

Create generic type from another type’s values in TypeScript

You can also create generic types from another type’s values in TypeScript, like this:

TypeScript
type Site = { url: 'wp.codingbeautydev.com'; age: number; topic: string; }; // 👇 type Site = 'string' | 'number' type Values = Site[keyof Site];
The Values type comes from the Site type's values.
The Values type comes from the Site type’s values.

How to Fix the “Unexpected reserved word ‘enum'” Error in JavaScript

The “Unexpected reserved word ‘enum'” syntax error happens in JavaScript happens because enum is not a valid keyword in JavaScript, but it is reserved.

The "Unexpected reserved word 'enum'" syntax error happening in JavaScript.

It was reserved in the ECMAScript specification in case it may become valid in the future.

If it wasn’t reserved, devs could start using it as variable names in their code – making future keyword use impossible!

JavaScript
// ❌ SyntaxError: Unexpected reserved word 'enum' enum Color { Red, Blue, Green } const color = Color.Red;

To fix it, represent the enumeration in another way, or change the file to TypeScript.

Fix: Create a JavaScript enum the right way

Enums are useful stuff, but since there’s no enum keyword in JS, we’ll have to find others way to create and use them.

One powerful way to create an enumeration is with an object with JavaScript symbol properties:

JavaScript
const daysOfWeek = { Mon: Symbol('Mon'), Tue: Symbol('Tue'), Wed: Symbol('Wed'), Thu: Symbol('Thu'), Fri: Symbol('Fri'), Sat: Symbol('Sat'), Sun: Symbol('Sun'), }; const dayOfWeek = daysOfWeek.Tue;

With JavaScript symbols, we make sure that the constants are always different values, as every symbol is unique.

No need to worry duplicates – pretty convenient, right?

If we used this:

JavaScript
const daysOfWeek = { Mon: 'Mon', Tue: 'Tue', Wed: 'Wed', Thu: 'Thu', Fri: 'Fri', Sat: 'Sat', Sun: 'Sun', }; const dayOfWeek = daysOfWeek.Tue;

Someone could easily reassign the object’s properties to something else, giving us something more to worry about.

Fix: Just use TypeScript

Ah, TypeScript.

Alway there for us. Filled to the top with juicy modern stuff.

I mean enums aren’t so modern, but it’s one thing TS has that JS doesn’t.

Our first JS code runs flawlessly in TypeScript.

TypeScript
// ✅ No error - enums all the way! enum Color { Red, Blue, Green } const color = Color.Red;

So, if you really need that enum keyword – even though much of the TypeScript community seems to frown on it – change that file extension.

Oh, it could even be that it’s TypeScript you wanted all along. As it happened here.

Here, this person was new to TypeScript on Node (we’ll all been there) and ran his TS file with the node command directly.

Well, Node didn’t care about the extension and just treated the entire thing like a JavaScript file.

The easy solution was to compile it first with tsc before running node on the JS output. Or to use ts-node on the TypeScript file directly.

Key takeaways

So, the few things to keep in mind on fixing the “Unexpected reserved keyword ‘enum'” error in JavaScript:

  1. enum is a no-go in JavaScript (for now): JavaScript doesn’t have enum. It’s reserved for future use.
  2. Use objects with symbol properties: Want to create enumerations in JavaScript? Use objects with symbol properties.
  3. Symbols keep your code safe: Symbols are unique. They stop others from messing with your object’s properties.
  4. TypeScript has enum: Need enum? Switch to TypeScript. It’s got your back.
  5. Remember to compile TypeScript: Using TypeScript for Node.js? Compile your TypeScript files first. Or quickly use ts-node.

How to easily get the current route in Next.js

Getting the current route in a web application is important for managing user sessions, handling authentication, and dynamically displaying UI elements.

Let’s how see how easy it is to get the current route or pathname in our Next.js app.

In this article

Get current route in Next.js Pages Router component

We can get the current route in a Next.js component with the useRouter hook:

src/pages/blog.tsx
import Head from 'next/head'; import { useRouter } from 'next/router'; export default function Page() { const { pathname } = useRouter(); return ( <> <Head> <title>Next.js - Coding Beauty</title> <meta name="description" content="Next.js Tutorials by Coding Beauty" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> Welcome to Coding Beauty <br /> <br /> Pathname: <b>{pathname}</b> </main> </> ); }

Get current route in Next.js App Router component

To get the current route in a Next.js app router component, use the usePathname hook from next/navigation:

src/app/amazing-url/page.tsx
'use client'; import React from 'react'; import { Metadata } from 'next'; import { usePathname } from 'next/navigation'; export const metadata: Metadata = { title: 'Next.js - Coding Beauty', description: 'Next.js Tutorials by Coding Beauty', }; export default function Page() { const pathname = usePathname(); return ( <main> Welcome to Coding Beauty 😄 <br /> <br /> Route: <b>{pathname}</b> </main> ); }

We need 'use client' in Next.js 13 App Router

Notice the 'use client' statement at the top.

It’s there because all components in the new app directory are server components by default, which means we can’t access client-side specific APIs.

We’ll get an error if we try to do anything interactive with useEffect or other hooks, as it’s a server environment.

Get current route in Next.js getServerSideProps

To get the current route in getServerSideProps, use req.url from the context argument.

src/pages/amazing-url.tsx
import { NextPageContext } from 'next'; import Head from 'next/head'; export function getServerSideProps(context: NextPageContext) { const route = context.req!.url; console.log(`The route is: ${route}`); return { props: { route, }, }; } export default function Page({ route }: { route: string }) { return ( <> <Head> <title>Next.js - Coding Beauty</title> <meta name="description" content="Generated by create next app" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.png" /> </Head> <main> Welcome to Coding Beauty 😃 <br /> Route: <b>{route}</b> </main> </> ); }
The current route printed in the console

How to easily get the current URL in Next.js

We use the current URL in a web app to track user activity, maintain history, or modify displayed elements based on route. So, let’s see how to quickly get the current URL in a Next.js app.

In this article

Get current URL in Next.js Pages Router component

To get the current URL in a Next.js component, use the useUrl hook from the nextjs-current-url package:

With pages directory:

src/pages/index.tsx
import { useUrl } from 'nextjs-current-url'; import Head from 'next/head'; export default function Home() { const { href: currentUrl, pathname } = useUrl() ?? {}; return ( <> <Head> <title>Next.js - Coding Beauty</title> <meta name="description" content="Next.js Tutorials by Coding Beauty" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.png" /> </Head> <main> Welcome to Coding Beauty 😄 <br /> <br /> URL: <b>{currentUrl}</b> <br /> pathname: <b>{pathname}</b> </main> </> ); }
The current URL is displayed on the Next.js page.

useUrl() returns a URL object that gives us more info on the current URL.

Get current URL with useState and window.location.href

We can also get the current URL in a client component using useState and window.location.href.

src/pages/index.tsx
import Head from 'next/head'; import { useRouter } from 'next/router'; import { useEffect } from 'react'; export default function Home() { const [currentUrl, setCurrentUrl] = useState<string | null>(null); const { pathname } = useRouter(); useEffect(() => { setCurrentUrl(window.location.href); }, []); return ( <> <Head> <title>Next.js - Coding Beauty</title> <meta name="description" content="Next.js Tutorials by Coding Beauty" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> Welcome to Coding Beauty 😄 <br /> <br /> URL: <b>{currentUrl}</b> <br /> pathname: <b>{pathname}</b> </main> </> ); }

The window.location.href property returns a string containing the entire page URL, and we use the useState and useEffect hooks to create and set state for storing the current URL.

window.location property

window.location has other properties that tell you more about the URL. Like:

  • pathname: the path of the URL after the domain name and any optional port number. Query and fragment identifier not included.
  • protocol: URL‘s protocol scheme, like https: or mailto:. Doesn’t include the //.
  • hostname: the URL‘s domain name without the port number.

Here’s an example where we use some of these properties:

src/pages/index.tsx
import { getUrl } from '@/lib/utils/get-url'; import { NextPageContext } from 'next'; import Head from 'next/head'; import { useEffect, useState } from 'react'; export function getServerSideProps(context: NextPageContext) { return { props: { currentUrl: getUrl({ req: context.req! })?.href, }, }; } export default function Home() { const [myLocation, setMyLocation] = useState<Location | null>(null); useEffect(() => { setMyLocation(window.location); }); return ( <> <Head> <title>Next.js - Coding Beauty</title> <meta name="description" content="Next.js Tutorials by Coding Beauty" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.png" /> </Head> <main> You are currently accessing <b>{myLocation?.href}</b> 😃 <br /> Pathname: <b>{myLocation?.pathname}</b> <br /> Protocol: <b>{myLocation?.protocol}</b> <br /> Hostname: <b>{myLocation?.hostname}</b> </main> </> ); }
Display various segments of the current URL in a Next.js page.

We need useEffect to get the current URL

Pages render on both the server and client in Next.js, so when the server renders the page, there’s no window object available.

So you’ll get a “window is not defined” error if you try to use window before hydration:

"window is not defined" error in Next.js page

That’s why we use useEffect – to wait till mounting/hydration is done.

What’s hydration?

Hydration is when a server-generated web page gets extra client-side features added by the user’s web browser. Features like event listeners, client-side routing, etc.

Get current URL in Next.js App Router component

To get the current URL in a Next.js app router component, we can also use the useUrl hook from the nextjs-current-url library.

src/app/page.tsx
'use client'; import React from 'react'; import { useUrl } from 'nextjs-current-url'; import { Metadata } from 'next'; export const metadata: Metadata = { title: 'Next.js - Coding Beauty', description: 'Next.js Tutorials by Coding Beauty', }; export default function Page() { const { pathname, href } = useUrl() ?? {}; return ( <main> Welcome to Coding Beauty <br /> <br /> URL: <b>{href}</b> <br /> route: <b>{pathname}</b> </main> ); }
The current URL is displayed on the Next.js app router component

Next.js App Router: We need 'use client'

Notice the 'use client' statement at the top.

It’s there because all components in the new app directory are server components by default, so we can’t use any client-side specific APIS.

We’ll get an error if we try to do anything interactive with useEffect or other hooks like useUrl, because it’s a server environment.

Get current URL in Next.js getServerSideProps

To get the current URL in getServerSideProps of a Next.js page, use the getUrl function from the nextjs-current-url library.

src/pages/amazing-url.tsx
import { NextPageContext } from 'next'; import Head from 'next/head'; import { getUrl } from 'nextjs-current-url/server'; export function getServerSideProps(context: NextPageContext) { const url = getUrl({ req: context.req }); return { props: { url: url.href, }, }; } export default function Home({ url }: { url: string }) { const urlObj = new URL(url); const { pathname } = urlObj; return ( <> <Head> <title>Next.js - Coding Beauty</title> <meta name="description" content="Generated by create next app" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.png" /> </Head> <main> Welcome to Coding Beauty 😃 <br /> <br /> URL: <b>{url}</b> <br /> Route: <b>{pathname}</b> </main> </> ); }
The current URL is displayed on the Next.js page from getServerSideProps()

Let’s check out some more properties of URL:

src/pages/amazing-url.tsx
import { NextPageContext } from 'next'; import Head from 'next/head'; import { getUrl } from 'nextjs-current-url/server'; export function getServerSideProps(context: NextPageContext) { const url = getUrl({ req: context.req }); return { props: { url: url.href, }, }; } export default function Home({ url }: { url: string }) { const urlObj = new URL(url); const { pathname, href, protocol, hostname, search, hash } = urlObj; return ( <> <Head> <title>Next.js - Coding Beauty</title> <meta name="description" content="Generated by create next app" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.png" /> </Head> <main> Welcome to Coding Beauty 😃 <br /> <br /> URL: <b>{href}</b> <br /> Pathname: <b>{pathname}</b> <br /> Protocol: <b>{protocol}</b> <br /> Hostname: <b>{hostname}</b> <br /> Search: <b>{search}</b> <br /> Hash: <b>{hash}</b> </main> </> ); }

Here’s what these properties do:

  • href: the complete URL, including the protocol, hostname, port number, path, query parameters, and fragment identifier.
  • protocol: URL’s protocol scheme, like https: or mailto:. Doesn’t include the //.
  • hostname: the URL’s domain name without the port number.
  • pathname: the URL’s path and filename without the query and fragment identifier.
  • search: the URL’s query parameters. Includes the ?
  • hash: the fragment identifier, the part after the #.
Various properties of the current URL are displayed on the Next.js page.

Note: As you can see it’s not possible to get the hash/fragment in getServerSideProps because the browser never sends the part after the # to the server. That’s why there’s no hash here. We’d have to get the current URL in the client-side to access the fragment identifier.

How to Fix the “Unknown file extension .ts” Error in ts-node

The “Unknown file extension .ts” error occurs in ts-node occurs when "type": "module" is set in your package.json file. To fix it, run the TypeScript file with ts-node --esm my-file.ts, or remove "type": "module" from your package.json file.

For example, in a project with this package.json file:

package.json
{ "name": "cb-js", "version": "1.0.0", "main": "index.js", "type": "module", "license": "MIT", "devDependencies": { "prettier": "^2.8.1" } }

If you have a TypeScript file in your project, e.g., my-file.ts:

my-file.ts
const num: number = 10; console.log(num ** 2);

Running the ts-node index.ts command will result in the ERR_UNKNOWN_FILE_EXTENSION TypeError in ts-node:

The ERR_UNKNOWN_FILE_EXTENSION TypeError occurs.
The ERR_UNKNOWN_FILE_EXTENSION TypeError occurs.

To fix the “Unknown file extension ‘.ts'” error in ts-node, run ts-node with the --esm option set:

Shell
ts-node --esm my-file.ts # Or ts-node-esm my-file.ts # Or node --loader ts-node/esm my-file.ts
Running ts-node in esm mode.
Running ts-node in esm mode.

To avoid using the --esm flag, add the following to your tsconfig.json file:

tsconfig.json
{ // other settings... "ts-node": { "esm": true, "experimentalSpecifierResolution": "node" } }

After doing this, you’ll be able to run the TypeScript file with only ts-node:

Shell
ts-node my-file.ts
Running the TypeScript file with only ts-node.
Running the TypeScript file with only ts-node.

You may also need to add one or more of the following options to your tsconfig.json file:

tsconfig.json
{ // other settings.. "compilerOptions": { // other compiler options... "esModuleInterop": true, "module": "ESNext", // "module": "CommonJS" should work too "moduleResolution": "Node" }, "include": ["/**/*.ts"], "exclude": ["node_modules"] }

Remove "type": "module" from tsconfig.json file

Alternatively, instead of doing all of the above, you can simply remove the "type": "module" field from your package.json file to fix the ERR_UNKNOWN_FILE_EXTENSION error in ts-node.

tsconfig.json
{ "name": "cb-js", "version": "1.0.0", "main": "index.js", // removed: "type": "module", "license": "MIT", "devDependencies": { "prettier": "^2.8.1" } }

And you’ll be able to run the TypeScript file with ts-node successfully.

Compile TypeScript files into JavaScript

Another way to avoid ERR_UNKNOWN_FILE_EXTENSION is to stop using ts-node altogether. Instead, you can compile your TypeScript files with tsc and run the JavaScript output with node – the classic way.

Shell
# Compile with tsc npx tsc --outDir dist my-file.ts # Run with node node dist/my-file.ts

Basic TypeScript compilation setup

Here’s a great way to set up your project for easily compiling and debugging TypeScript files.

First, install the TypeScript compiler:

Shell
npm i tsc

Then specify the src dir and out dir in tsconfig.json, and enable source maps for seamless Typescript debugging:

tsconfig.json
{ "compilerOptions": { // ... other options "rootDir": "src", // Location of TypeScript files "outDir": "dist", // Location of compiled JavaScript files "sourceMap": true // Generate sourcemaps } }

Finally, create a start NPM script that automatically runs the tsc and node commands one after the other:

JavaScript
{ // ... other options "scripts": { "start": "tsc && node index.js" } }

Now you can run the script easily with npm start.

And you can debug TypeScript in VSCode too.

How to Get an Object Value By Key in TypeScript

You can easily get an object’s value by a key in Typescript using bracket notation, i.e., obj['key'], obj[myVar], etc. If the key exists, you will get the corresponding value back.

For example:

TypeScript
type Car = { name: string; maxSpeed: number; color: string; }; const car: Car = { name: 'CB Flash', maxSpeed: 200, color: 'blue', }; console.log(car['name']); // CB Flash // Dot notation console.log(car.name); // CB Flash // Get value by variable key const prop = 'name'; console.log(car[prop]); // CB Flash // Computed property key const val = car[3 > 1 ? 'name' : 'maxSpeed'] console.log(val) // CB Flash

Dot notation property access

There are two ways to get an object’s value by a property key in TypeScript: dot notation and bracket notation.

In dot notation, we access an object value with the obj.propKey syntax.

TypeScript
type Car = { name: string; maxSpeed: number; color: string; }; const car = { name: 'CB Flash', maxSpeed: 200, color: 'blue', }; console.log(car.name); // CB Flash console.log(car.maxSpeed); // 200 console.log(car.color); // blue

With the obj.propKey syntax, the propKey must be a valid TypeScript identifier. Otherwise, a syntax error will be thrown:

TypeScript
type Car = { [propKey: string]: string }; const car: Car = {}; car.100 = 'go faster'; // ❌ SyntaxError console.log(car.100); // ❌ SyntaxError

propKey can also be a reserved keyword, like let, var, async, etc.

TypeScript
type Car = { [propKey: string]: string }; const car: Car = {}; car.let = 'works'; car.await = 'works too'; console.log(car.let); // works console.log(car.await); // works too

Bracket notation property access

In bracket notation, we access the property value with the obj[expression] syntax. The expression should evaluate to a string or Symbol that represent the property’s key.

TypeScript
type Car = { name: string; maxSpeed: number; color: string; }; const car: Car = { name: 'CB Flash', maxSpeed: 200, color: 'blue', }; console.log(car['name']); // CB Flash console.log(car['maxSpeed']); // 200 console.log(car['color']); // blue

Unlike dot notation, with bracket notation, we can access keys that are not valid TypeScript identifiers, like numbers and keys containing spaces.

TypeScript
type Car = { [propKey: string]: string }; const car: Car = {}; car['100'] = 'go faster'; car['year produced'] = 2022; console.log(car['100']); // go faster console.log(car['year produced']); // 2022

Computed property names

The expression we put in-between the brackets can be as complex as possible, as long it evaluates to a string or Symbol.

For example, we can put a ternary expression in-between the brackets:

TypeScript
type Car = { name: string; maxSpeed: number; color: string; }; const car: Car = { name: 'CB Flash', maxSpeed: 200, color: 'blue', }; const num = 3; const val = car[num > 1 ? 'name' : 'maxSpeed']; console.log(val); // CB Flash

Note: If the expression to the left of the ? is truthy, the ternary operator returns the value to the left. Otherwise, it returns the value to the right.

The ternary expression evaluates to the 'name' key, so the corresponding property value is returned.

You can also this computed property names approach to set a new property on a object.

TypeScript
type Car = { [propKey: string]: string | number; }; const car: Car = {}; const num = 7; car[num > 10 ? 'name' : 'maxSpeed'] = 500; console.log(car['name']); // undefined console.log(car['maxSpeed']); // 500

How to Fix the “Cannot find name ‘console'” Error in TypeScript

The “cannot find name ‘console'” error occurs when you try to access the global console object in a TypeScript file. To fix it, install the @types/node NPM package for Node.js environments, or add 'DOM' to the lib array in your tsconfig.json for browser environments.

The "cannot find name 'console'" TypeScript error occuring in VSCode.
The “cannot find name ‘console'” TypeScript error occuring in VSCode.
index.ts
/* * Cannot find name 'console'. Do you need to change your * target library? Try changing the 'lib' compiler option * to include 'dom'.ts(2584) */ console.log('coding beauty');

Install Node.js typings

If your code is running in a Node.js environment, you can fix the “cannot find name ‘console'” error by running the following command at the root of your project directory.

Shell
npm i -D @types/node # Yarn yarn add --dev @types/node

This should resolve the error for Node.js runtimes.

Add typings to types array in tsconfig.json

In some cases, this is all you need to fix the error. But if it persists, you might need to add the newly installed typings to the types array of your tsconfig.json file.

Including 'node' string in the tsconfig.json types array will make the Node.js typings visible to the TypeScript compiler.

tsconfig.json
{ "compilerOptions": { "types": [ // other types... "jest" ] // other settings... } }

Add 'DOM' to lib array in tsconfig.json file

If your code is running in a browser, trying adding a 'DOM' string to the lib array in your tsconfig.json file.

tsconfig.json
{ "compilerOptions": { "lib": [ // other libs... "ES6", "DOM" ], // other settings... }, }

Doing this tells TypeScript that your code is client-side code, and it should provide a set of type definitions for built-in JavaScript APIs found in browser environments.

Restart code editor

If the error persists after trying out all these solutions, restarting your IDE or code editor might help.

Conclusion

To fix the “cannot find name ‘console’ error” in TypeScript, install Node typings if your code runs in Node.js, or add the 'DOM' string to your types array in your tsconfig.json if running in a browser.

How to Fix the “Cannot Find name ‘describe'” Error in TypeScript

To fix the “cannot find name ‘describe'” error, install the type definitions for your testing framework, and then add the definitions to the types array in your tsconfig.json file.

This error happens if you try to use the describe() function in a TypeScript file, but type definitions for the package are missing.

The "cannot find name 'describe'" error happening in a TypeScript file in VS Code.
index.ts
/* Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`. ts(2582) */ describe('example', () => { it('adds two numbers together', () => { expect(2 + 2).toBe(4); }); }); 

Install the type definitions for the testing framework you’re using by running one of the following commands at the root of your project directory.

Shell
# 👇 Jest npm i -D @types/jest jest # 👇 Mocha npm i -D @types/mocha mocha # Yarn # 👇 Jest yarn add --dev @types/jest jest # 👇 Mocha yarn add --dev @types/mocha mocha

Add typings to types array in tsconfig.json

In some cases, this is all you need to fix the error. But if it persists, you might need to add the newly installed typings to the types array of your tsconfig.json file.

So if you’re using Jest, you’ll add a jest string to the types array, and then your tsconfig.json file will look something like this:

tsconfig.json
{ "compilerOptions": { "types": [ // ... other types "jest" ] // ..other settings } }

If you’re using Mocha too, you’ll add a mocha string to the types array.

tsconfig.json
{ "compilerOptions": { "types": [ // ... other types "mocha" ] // ..other settings } }

Include test files

If the error still doesn’t go away after doing this, make sure that TypeScript is not ignoring the directory containing your test files.

If you’ve set the include array in your tsconfig.json file, make sure the patterns specified in this array match the directory where your test files are located.

For example, if your test files are located in a src directory, TypeScript will detect them with a configuration like this:

tsconfig.json
{ "compilerOptions": {}, "include": ["src/**/*"], }

But if they’re located in a tests directory, we’ll need to add an additional glob pattern to make TypeScript detect them:

tsconfig.json
{ "compilerOptions": {}, "include": [ "src/**/*", "tests/**/*" ], }

We can also include glob patterns to match files with a specific ending or extension.

For example, we can include all files ending with .spec.ts and .test.ts with this config:

tsconfig.json
{ "compilerOptions": {}, "include": [ "src/**/*", "**/*.spec.ts", "**/*.test.ts" ], }

If you’ve set the exclude array in your tsconfig.json file, make sure that none of the patterns in the array match the directory containing the test files, as this will prevent TypeScript from detecting them.

For example, in the tsconfig.json file below, files ending with .spec.ts have been excluded, so TypeScript will ignore them and the error will occur when you attempt to use describe() in them.

tsconfig.json
{ "compilerOptions": {}, "include": [ "src/**/*" ], "exclude": [ "**/*.test.ts" ], }

We’ll fix this issue by simply moving the pattern string from exclude to include:

tsconfig.json
{ "compilerOptions": {}, "include": [ "src/**/*", "**/*.test.ts" ], }

Import module in file

Instead of adding the typings to the types array, you can also import them at the top of the file where you are using describe().

So if we’re using Jest, we’ll add an import 'jest' line at the beginning of the file.

index.ts
// 👇 import 'jest'; // ✅ No error describe('example', () => { it('adds two numbers together', () => { expect(2 + 2).toBe(4); }); }); 

If we’re also using Mocha, we’ll add an import 'mocha' line:

index.ts
// 👇 import 'mocha'; // ✅ No error describe('example', () => { it('adds two numbers together', () => { expect(2 + 2).toBe(4); }); }); 

Restart IDE

If the error persists after doing all of this, restarting your IDE might help.