Utilizing both Typescript and javascript in a unified project

Recently, I've been working on a NodeJS project and wanted to incorporate TypeScript files. In my initial attempt, I created a TypeScript file with the following content:

utilts.ts :

export const delimitify = ( strings:Array<string>, delimiter:string ):string => 
strings.join(delimiter);
export const slugify = ( strings:Array<string> ):string => strings.join('_');
export const hyphenify = ( strings:Array<string> ):string => strings.join('-');
export const andify = ( strings:Array<string> ):string => strings.join('&');
export const orify = ( strings:Array<string> ):string => strings.join('|');

In my test file, I wrote the following:

/__test__/utilts.test.js

import {
  delimitify
} from "../utilts";

describe(
  "delimitify",
  () => {
    it(
      "must return string delimited by hyphen", 
      () => {
        const result = delimitify(['1', '2', '3'], '-');
        
        expect(result).toBe('1-2-3')
      }
    );
  }
);

Upon compilation, an error was raised:

SyntaxError: /home/brunolnetto/github/quivero/prego/utils/testing/utilts.ts: Unexpected token, expected "," (2:35)

      1 |
    > 2 | export const delimitify = ( strings:Array<string>, delimiter:string ):string => strings.join(delimiter);
        |                                    ^
      3 | export const slugify = ( strings:Array<string> ):string => strings.join('_');
      4 | export const hyphenify = ( strings:Array<string> ):string => strings.join('-');
      5 | export const andify = ( strings:Array<string> ):string => strings.join('&');

    > 1 | import {
        | ^
      2 |   delimitify
      3 | } from "../utilts";

It appears to be a straightforward fix. This experience could serve as a lesson for others in the community. 😊

Answer â„–1

In order for Node to execute your code, TypeScript must first be compiled into JavaScript.

To set up TypeScript:

npm install typescript && npx tsc --init

To run your project: npx tsc && node ./build/index.js

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

ElevationScroll expects the 'children' prop to be a single child component of type 'ReactElement<any, string>'

I am currently working on integrating the Elevate AppBar from Material UI into my application using the following code: interface Props { children: React.ReactElement; } export const ElevationScroll = ({children}: Props) => { const trigger = u ...

What is the process for retrieving information from an observable array?

I am currently developing an application with a Python backend and Angular frontend. The main functionality of the app involves retrieving FIFA players from a MongoDB using the getLoyalPlayers function. Below is the snippet from the loyalty.component.ts f ...

The updated value in useState keeps reverting to its original value

I am currently developing an ecommerce website using Next.js. In the product grid section, I have implemented a filter option that enables users to select a specific category. However, I am facing challenges with updating the products variable when I try t ...

Angular2 authguards encountering issues when trying to run asynchronous functions

I need a way to safeguard my routes by verifying if a user is logged in from the server, but I'm facing issues with asynchronous functions not executing properly. Below is the code snippet that's causing trouble: canActivate (route: ActivatedRo ...

The enigma of the mysterious karma provider error

As a newcomer to unit testing in JavaScript, AngularJS, and Karma, I have successfully written passing tests for controllers. However, when trying to test services, I encountered an error: Unknown provider <- nProvider <- User. The User service is th ...

Troubleshooting issue: Angular Typescript object array filter functionality malfunctioning

I am currently attempting to filter an array of objects based on a specific value. Interestingly, out of the console.log outputs provided below, only the first one is yielding the expected result: console.log('log1: ', sf); console.log('log ...

Is it possible to meet the requirements of a specific interface using an enum field as the criteria?

I've been struggling to create a versatile function that can return a specific interface based on an enum argument, but all my attempts have failed. Could it be possible that I missed something or am simply approaching it the wrong way? If I try to ...

What is the correct way to type "this" to ensure it works properly when called in a subclass method?

Let's consider including an extension method to the existing Object: declare global { interface Object { ext<B>(f: (x: this) => B): B; } } The aim is to apply it as shown below: "x".ext(x => x.toUpperCase()) //or (1).ext(x => ...

Angular - a simple method to determine the number of non-empty inputs in a complex template-driven form

As I work on multiple substantial Angular 11 template forms containing basic inputs like text, radiolists, and checkboxes, I am looking for the most effective method to calculate the percentage of completed inputs while the user is actively engaging with ...

The pairing of Transpiller and Internet Explorer 8 is like a dynamic

In starting my new project, I am considering using BabelJS. However, there is a significant requirement that must be met: it needs to be compatible with IE8. ISSUE: Babel compiles ES6 to ES5, but the support for ES5 on IE8 is lacking. Are there any alter ...

Function that returns an Observable<Boolean> value is null following a catch block

Why is the login status null instead of false in this method? // In the method below, I am trying to return only true or false. isLoggedIn(): Observable<boolean> { return this .loadToken() .catch(e => { this.logger ...

Error in Typescript: Issue with Object.fromEntries Typescript Error

In my TypeScript code, I have a function that utilizes Object.fromEntries to simplify a complex response object and organize it by using a substring of the child object key. let Newresult = res.map(object => Object.fromEntries(Object.entries(object).ma ...

The comparison between "rxjs-tslint" and "rxjs-tslint-rules" npm packages

Previously, I utilized the rxjs-tslint-rules package to identify RxJS-related issues in my projects. This package was included in the devDependencies section of my projects' package.json files. Now, there is a new rxjs-tslint package that introduces ...

The alignment of the first and second steps in Intro.js and Intro.js-react is off

There seems to be an issue here. Upon reloading, the initial step and pop-up appear in the upper left corner instead of the center, which is not what I anticipated based on the Intro.js official documentation. https://i.stack.imgur.com/ICiGt.png Further ...

When accessing APIs, create an array of observables for each user call and then trigger a function once all are successfully resolved

As I aim to generate a list of observables while a user engages with the webpage, I am faced with the challenge of individually subscribing to each observable, but desiring another function to execute after individual or multiple simultaneous API calls are ...

Is there a way to extract data from a single line?

In my code, I have a simple object retrieved like this: getSelectedRecipients(event) { this.aliasesService.getRecipients(event.nr) .subscribe( res => { this.recipients = res; this.isVisible = true; }, err =&g ...

Is it advisable to avoid circular imports in typescript development?

After spending 4 long hours troubleshooting a TypeScript error, I finally found the root cause. Object literal may only specify known properties, and 'details' does not exist in type 'Readonly<{ [x: `details.${string}.value`]: { value: st ...

Elegantly intersect two types of functions in Typescript

Two function types are defined as follows: wrapPageElement?( args: WrapPageElementBrowserArgs<DataType, PageContext, LocationState>, options: PluginOptions ): React.ReactElement .. and .. wrapPageElement?( args: WrapPageElementNodeArgs<Data ...

Copying the position and rotation of a mesh from one world to another in ThreeJS

In my setup, I currently have 3 meshes named cube(a), tempSphere(b), and m_mesh(c). Mesh a and b are grouped together with a as the parent mesh. I have managed to update the location, rotation, and position of the group, so that meshes a and b automatical ...

Tips for creating a custom script in my React Native application

My React Native app requires a script to generate static files during the release process. The app is a game that utilizes pre-computed boards, which are resource-intensive to compute. Therefore, I am developing a script that will create these boards and s ...