Is there a way to specify the default ES version for the TypeScript compiler (tsc)?

Over the past day, I have dedicated a significant amount of time to understanding:

  • the inner workings of Visual Studio Code
  • the ins and outs of TypeScript
  • the functionality of the TypeScript Compiler (tsc)
  • how these three components intertwine with each other

In less than 24 hours (!), I successfully managed to write some basic TypeScript code and compile it into Javascript.

My excitement was slightly dampened when I realized that the TypeScript Compiler (tsc) not only compiled the static type labels but also transpiled:

  • const

to:

  • var

I expressed feeling dampened, but truthfully, I was actually mildly shocked.

Later on, I discovered that the default transpilation target for tsc is ECMAScript 3.

It seems that I can maintain my const declarations constant by using the --target flag when invoking tsc:

tsc my-first-typescript.ts --target es6

However, constantly having to include --target es6 (or --target es11) every time I call upon tsc is not ideal.

Is there a method to establish the default transpilation target version for tsc so that it does not automatically revert to outdated javascript practices?

Answer №1

Changing the global default settings for TypeScript may not be feasible, but you can customize specific project configurations by creating a tsconfig.json file in the project root. More information on how to do this can be found in the Project Configuration section of the TypeScript Handbook. For example:

{
    "compilerOptions": {
        "target": "ES2015"
    }
}

If you prefer not to create your own configuration from scratch, you can use the tsconfig/bases project on GitHub, which provides pre-made configurations for different types of projects.

Answer №2

Unable to find a direct way to configure tsc itself, but creating a global variable tscFlags does the job effectively.

Although this example is in Powershell, there should be an equivalent method in bash/unix environments.

To Create a Global Array in Profile/Imported Module:

$tscFlags = @(
    # Flags
    '--noEmitOnError'
    '--strict'
    '--alwaysStrict'
    '--noFallthroughCasesInSwitch'
    '--noImplicitAny'
    '--noImplicitReturns'
    '--noImplicitThis'
    '--noPropertyAccessFromIndexSignature'
    '--noUncheckedIndexedAccess'
    '--noUnusedLocals'
    '--noUnusedParameters'
    '--strictBindCallApply'
    '--strictFunctionTypes'
    '--strictNullChecks'
    '--strictPropertyInitialization'
    # Options
    '-t'
    'ES2020'
)

PS C:\> tsc <file.ts> @tscFlags

If needed, additional flags can be manually added before or after the 'splatted' @tscFlags call.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to create a typesafe Map in TypeScript with a key and value both being of the same generic type X?

The desired outcome should be as follows: const newObj: ??? = { [Fruit<Apple>]: Taste<Apple>, [Fruit<Banana>]: Taste<Banana>, } const selectedKey: Fruit<Apple> = ...; newObj[selectedKey] // should only return Taste<A ...

Returning a 'never' type from a function in React using Typescript

Basically, I have a function that initiates the OAuth flow (redirecting to Google OAuth login page, for example): async function signIn() { // start OAuth flow } And let's say I want to use it in a useEffect hook like this: ... useEffect(() => { ...

Waiting for all promises in TypeScript and returning the results

Working on some Node.Js code, I decided to utilize promise.all for parallel execution. To illustrate the issue, here's a snippet from my code: in MyService.ts @Injectable() export class MyService { constructor(private readonly anotherService: An ...

Retrieving live comments from YouTube streams for a customized React application

Currently working on developing a React Webapp to organize and showcase superchats during a live stream. My initial attempt involved utilizing the YouTube LiveChat API, but I hit a roadblock as it requires authentication from the live stream owner, which ...

"Angular encountered an error while attempting to access the property 'data' from an undefined

I'm encountering an issue when trying to retrieve data from a JSON file. Upon clicking a button to display the data in a textarea, the first click does not yield any result, but subsequent clicks work as expected. The program functions by fetching an ...

Running unit tests using Typescript (excluding AngularJs) can be accomplished by incorporating Jasmine and Webpack

While there is an abundance of resources on how to unit test with Webpack and Jasmine for Angular projects, I am working on a project that utilizes 'plain' TypeScript instead of AngularJs. I have TypeScript classes in my project but do not use c ...

What is the best way to pass dynamic values to a service constructor from a component?

After days of attempting to grasp 'the Angular paradigm', I still find myself struggling to understand something about services that are not singletons. It seems impossible for me to pass a runtime-determined value to a service constructor, as I ...

The C program runs perfectly on VS Code, however, it encounters issues when trying to run on Dev-C++

Upon trying to sum the votes received per candidate, I encountered a unique issue where the sum of votes became negative. Initially, I attempted to use the debugger in Dev-C++, but the program would halt after entering the votes. As an alternative, I decid ...

Facing Zone undefined Error while utilizing TestBed for Angular2 testing

Recently, I've been following the tutorial on https://angular.io/docs/ts/latest/guide/testing.html to create my first set of unit tests. Everything was going well until I reached the TestBed example. That's where things took a turn and I encounte ...

How can you upload information while specifying the status?

Within my config.ts file, the contents are as follows: export const keyOrders: {} = { "aa": { active: true, order: 0 }, "bb": { active: true, order: 1 }, "cc": { active: true, order: 2 }, "dd": { active: true, order: 3 }, "ee": { activ ...

Issue with SvelteKit: PageData not being refreshed in API response after initial render

I am relatively new to working with Svelte and SvelteKit, and I am currently trying to fetch data from an API. I have followed the SvelteKit todo sample code, which works well for the initial rendering and when clicking on an a tag. However, I am facing an ...

Matching packages with mismatched @types in Webpack 2: A comprehensive guide

Having trouble implementing SoundJS (from the createJS framework) in my TypeScript project using webpack 2. In my vendors.ts file, I have the following import: import "soundjs"; Among other successful imports. The @types definitions installed via npm a ...

Meta fields in the Vue Router

Is it feasible to create custom properties while defining routes for VueRouter? Specifically, I am interested in setting up a route structure like the one below, where I can specify a component for an optional property "menu" for most routes in my applicat ...

Unable to locate the _app.js file within my Next.js project

After using "npx create-next-app" to set up my NextJs project, I came across a situation where I needed to define TransactionContext in _app.js. However, I encountered the issue that this file is not included in my project. Any assistance would be greatly ...

Choosing to selectively trigger a function using TypeWriter

I have successfully implemented TypeWriter to generate TypeScript classes from my C# models. The template I am currently using is shown below: ${ using Typewriter.Extensions.Types; Template(Settings settings) { settings.IncludeProject ...

Harness the power of the Node.js Path module in conjunction with Angular 6

I'm currently facing an issue with utilizing the Path module in my Angular 6 project. After some research, I came across a helpful post detailing a potential solution: https://gist.github.com/niespodd/1fa82da6f8c901d1c33d2fcbb762947d The remedy inv ...

Choose a single entity from the ngrx store and display it in a separate template

I have been working on a blog application that utilizes ngrx for state management. Currently, there are two main objects stored in the application: { "posts": [...], "users": [...] } Now, I am looking to create a separate component spe ...

Invoke a custom AWS CodeBuild project in CodePipeline using a variety of parameters

Imagine having a CodePipeline with 2 stages structured like this: new codepipeline.Pipeline(this, name + "Pipeline", { pipelineName: this.projectName + "-" + name, crossAccountKeys: false, stages: [{ stageName: &apos ...

The declaration file for 'autobind-decorator' is missing in TypeScript and cannot be located

Having a bit of trouble with my Typescript project. I'm trying to import the 'autobind-decorator' package, but I hit a roadblock. When compiling, I keep running into this error: cannot find declaration file for 'autobind-decorator&ap ...

The toJSON function is not being invoked when inside a nested array

Currently, I am immersed in a typescript project and utilizing the toJSON and fromJSON methods to effectively parse my objects. A peculiar issue has arisen when employing JSON.stringify() on one of my classes, as it neglects to invoke the toJSON methods o ...