TypeScript Overview, News & Trends | The New Stack Wed, 14 Jun 2023 18:33:48 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 70% of Devs Using or Will Use AI, Says Stack Overflow Survey https://thenewstack.io/70-percent-of-developers-using-or-will-use-ai-says-stack-overflow-survey/ Wed, 14 Jun 2023 17:45:51 +0000 https://thenewstack.io/?p=22710894

Artificial intelligence is hot, and GitHub Copilot and ChatGPT are poised to benefit developers, according to Stack Overflow’s 2023 Developer

The post 70% of Devs Using or Will Use AI, Says Stack Overflow Survey appeared first on The New Stack.

]]>

Artificial intelligence is hot, and GitHub Copilot and ChatGPT are poised to benefit developers, according to Stack Overflow’s 2023 Developer Survey.

Adoption of the Lua and Rust programming languages spiked in 2023, as did that of the Python-based FastAPI framework, reported the latest global survey of more than 90,000 developers.

When asked about their plans to use AI tools in their development process, 44% of developers said they already do this and another 26% plan to do so soon.

When this group was asked what specific AI-powered developer tools they use, 55% mentioned GitHub Copilot, while 13% use Tabnine and 5% use Amazon Web Services CodeWhisperer. The other seven tools included in the survey were used by no more than 2%.

The gap between GitHub Copilot and similar tools is most noticeable when looking at how many of its users plan to continue using it — 72% of GitHub Copilot users want to use it in the upcoming year, as compared to only 53% of AWS CodeWhisperer users and 37% of Tabnine users.

AI search tools like ChatGPT were also highlighted in the study. Among respondents who are already using one of 11 different AI search tools Stack Overflow asked about, the following percentages of devs have used these tools in the past year:

About 78% of both ChatGPT and Phind users claim they will continue using the technology in the next year, which is higher than the 61% of Bard AI and 62% of Bing AI users expressing that type of loyalty.

Lua, Rust, TypeScript and Go Gain Users

Lua and Rust were among the fasted growing programming languages. Rust usage grew 40% in 2023 and its adoption rate now stands at 13% of developers. Meanwhile, Lua adoption rose 50%, to a still modest 6%.

Among languages with larger user bases, TypeScript and Go saw the largest gains; TypeScript adoption rose 12%, to 39% of developers. Go rose 19%, used by 13% of devs.

When it comes to web frameworks, Python-based FastAPI saw the most rapid growth, rising 48% to a still-modest 7% of developers surveyed. While not technically a framework, jQuery continues its steady decline, dropping 23%, to usage by 22% of developers.

Other notable changes include:

  • Docker adoption fell 19% over the last year, but 51% of developers in the 2023 study reported that they were using it. It remains incredibly popular among its core user base — 75% of developers that have used Docker in the last year have a desire to continue using it in the next 12 months. This tells us that even after several bumps in the hype cycle, Docker and containers are here to stay.
  • Use of Atlassian's Trello, a tool for asynchronous collaboration and project management, fell 42% since 2022, down to 19% of survey participants. Asana adoption also fell 36%, with only 5% using it in 2023.
  • Less significant declines were also seen by the leaders in this category, including Atlassian's Jira and Confluence, which may indicate a market consolidation and that developers are relying on fewer collaboration tools.
  • Adoption of popular package managers npm and Yarn are on the decline. Use of npm fell 24% to 49% of respondents and Yarn dropped 21% to 22% of respondents.

Heroku Usage Down 40% Since 2022's Report

Some of the biggest news coming out of the Stack Overflow survey is about the technologies and frameworks that have seen significant declines in usage.

Almost all of the cloud providers saw declines, but Heroku's was the worst. Only 12% of developers used Heroku in 2023, down 40% from the 2022 study. Even worse, only 22% of the technology's user base said they want to continue using it in the upcoming year.

Even the cloud leaders are taking a hit, with Google Cloud usage falling 11% compared to the previous year, Microsoft Azure dropping 9%, and Amazon Web Services declining 5%.

A new group of cloud platforms may be taking advantage of this slump. For the first time, Cloudflare (used by 15% of the survey participants), Vercel (used by 11%), Netlify (also used by 11%) and Germany's Hetzner (used by 4%) were included in the survey. Notably, Vercel and Hezner were the most admired cloud provider among those that survey participants were asked about.

The post 70% of Devs Using or Will Use AI, Says Stack Overflow Survey appeared first on The New Stack.

]]>
Dev News: A New Rust Release and Chrome 114 Updates https://thenewstack.io/dev-news-a-new-rust-release-and-chrome-114-updates/ Sat, 03 Jun 2023 16:00:47 +0000 https://thenewstack.io/?p=22709966

The Rust team released Rust 1.70.0 Thursday, and users should see “substantially improved performance” when fetching information from the crate.io

The post Dev News: A New Rust Release and Chrome 114 Updates appeared first on The New Stack.

]]>

The Rust team released Rust 1.70.0 Thursday, and users should see “substantially improved performance” when fetching information from the crate.io index.

That’s because this release makes Cargo’s “sparse” protocol enabled by default for reading the index from crates.io. Previously, using that protocol required configuration.

It comes with a caveat, though — the upgrade changes the path to the crate cache, so dependencies must be downloaded again. The Rust team suggested developers clear out the old registry paths once they’ve fully committed to using the sparse protocol.

Also OnceCell and its thread-safe counterpart OnceLock have been established for one-time initialization of shared data.

“These can be used anywhere that immediate construction is not wanted, and perhaps not even possible like non-const data in global variables,” the team noted. “Crates such as lazy_static and once_cell have filled this need in the past, but now these building blocks are part of the standard library, ported from once_cell’s unsync and sync modules.”

Other changes in this release:

  • IsTerminal is also stabilized;
  • The Cdebuginfo compiler option now has named levels of debug information, meaning you can now set the debut levels by name: “none” (0), “limited” (1), and “full” (2) as well as two new levels, “line-directives-only” and “line-tables-only.” These naming options aren’t yet available to be used via Cargo.toml, which is expected to be supported in the next release;
  • Stable and beta builds of Rust no longer allow unstable test options, making them truly nightly-only as documented;
  • A long list of stabilized APIs.

What’s New in Chrome 114

Chrome 114 is out now and Adriana Jara, a developer relations engineer with Chrome, outlined what frontend developers need to know.

First, in one line, developers can now improve text layouts. Developers don’t necessarily know the final size, font size or even language of a text, which can make it difficult to make headlines and text blocks look … well, balanced. Now, with text-wrap: balance, developers can request the browser to figure out the best balanced line-wrapping solution.

“The balanced text block is more pleasing to the eye of a reader,” Jara wrote. “It grabs attention better and is overall easier to read.”

Second, another new feature, CHIPS (Cookies Having Independent Partitioned State) enables opting-in to third-party cookies being partitioned by a top-level site using the new cookie attribute Partitioned, she explained. Previously, an embedded site could set a cookie on one site and use it from another, which created a cross-site tracking issue.

“While cross-site tracking is an issue, there are valid cross-site cookie needs which can be achieved in a privacy-preserving way with cookie partitioning,” Jara explained. “With CHIPS, when a user visits site A and embedded content from site C sets a cookie with the Partitioned attribute, the cookie is saved in a partitioned jar only for cookies that site C sets when it’s embedded on-site A. The browser would only send that cookie when the top-level site is A.”

Then when the user visits a new site that has embedded the C website, it does not receive the cookie it set when it was embedded in the first site.

Finally, Jara explained how the Popover API makes it easier to build transient user interface elements that are displayed on top of all other web app UI. Examples include user-interactive elements such as action menus, form element suggestions, content pickers, and teaching UI.

“The new popover attribute enables any element to be displayed in the top layer automatically,” Jara explained. “This means no more worrying about positioning, stacking elements, focus or keyboard interactions for the developer.”

TypeScript 5.1 Released

Last week, The New Stack shared that Typescript 5.1 RC was available. Well, it’s been released officially, and since then the TypeScript team has made a few adjustments.

“Since the RC, we’ve iterated slightly on our built-in refactorings to move declarations to existing files; however, we believe the implementation still needs some improvements,” wrote Daniel Rosenwasser, the senior program manager for TypeScript. “As a result, you may not be able to access it in most editors at the moment, and can only opt-in through using a nightly version of TypeScript.”

The plan is either to release a patch or incorporate the refactoring into TypeScript 5.2.

The post includes a summary of what’s new in TypeScript 5.1, including:

  • Easier implicit returns for undefined-returning functions.
  • Unrelated types for getters and setters.
  • Decoupled type-checking between JSX elements and JSX tag types.
  • Namespaced JSX attributes.
  • typeRoots are consulted in module resolution.
  • Linked cursors for JSX Tags.
  • Snippet completions for @param JSDoc tags.
  • A slew of new optimizations.

The post Dev News: A New Rust Release and Chrome 114 Updates appeared first on The New Stack.

]]>
Dev News: New Microsoft Edge Tools and Goodbye Node.js 16 https://thenewstack.io/dev-news-new-microsoft-edge-tools-and-goodbye-node-js-16/ Sat, 27 May 2023 13:00:34 +0000 https://thenewstack.io/?p=22709332

Microsoft’s web development team announced a number of changes that should make Edge faster while improving the developer experience, according

The post Dev News: New Microsoft Edge Tools and Goodbye Node.js 16 appeared first on The New Stack.

]]>

Microsoft’s web development team announced a number of changes that should make Edge faster while improving the developer experience, according to a presentation at Microsoft Build conference on Wednesday.

The updates include:

  • A built-in JSON Viewer is currently an experimental feature in Edge 114. Activating this feature will cause any URL that returns a JSON resource to load directly into the browser in the JSON viewer.
  • Microsoft Edge Dev Tools, which are built into the browser. “It’s a set of tools that appear next to the rendered webpage in the browser, and provide a powerful way to inspect and debug web pages and web apps,” Zohar Ghadyali, program manager on the Microsoft Edge Dev Tools team, said. “As a non-exhaustive list, you can use the dev tools to inspect, tweak and change the styles of elements in the web page using live tools with a visual interface, inspect network traffic and see the location of problems like resources that fail to load and debug your JavaScript using breakpoint debugging and with a live console.” In all, there are 33 tools.
  • Focus Mode. To help manage the visual overhead of the 33 tools, the browser also offers Focus Mode, wherein the top bar is customizable to hold a developer’s primary tools and the bottom bar contains the rest. “In addition to moving the doc location of dev tools, you can also customize the positioning of the activity bar,” Ghadyali said. “If you like the older Dev Tools UI and you like the horizontal toolbar, you can leave the activity bar in this orientation. However, if you like the way VS code is organized, instead, you can move the activity bar to a vertical orientation.” Focus Mode also incorporates a quick view function that allows the developer to look at two tools simultaneously.

There are also new features in dev tools to improve performance and add context to things such as enhanced traces, including .devtools file, which is the new file format for enhanced traces from Microsoft Edge.

“The key benefits of enhanced traces are that even if server-side changes are made, you’re preserving the state of your source code and the state of your webpage,” Ghadyali said. “This means you can package and share self-contained Dev Tools instances when collaborating with your teammates or co-workers.”

This solves the “it doesn’t work for me” problem. Instead of getting a rogue console error and then trying to show a colleague how you triggered that state, you can instead export and enhance trace and share the dot Dev Tools file with them, and the state will be preserved, Ghadyali explained.

Another new feature is the “select your stats” feature in the performance tools, which is designed to help developers understand what is happening during long-running recalculate style events in the performance tool.

There’s also support for faster debugging using source maps, which map from the transformed source to the original source, allowing the browser to reconstruct the original source and present the reconstructed original in a debugger.

Edge also has a new experimental crash analyzer tool.

“With the crash Analyzer tool, you can input a JavaScript stack trace, like those that you get for non-fatal JavaScript exceptions, and have your source maps applied to the salary so that you can debug faster,” said Rob Paveza, a principal software engineering manager at Microsoft.

Paveza also shared with the audience anti-patterns that can slow web performance.

Vercel to Deprecate Node.js 16

Bad news for those who don’t want to upgrade: Vercel is deprecating Node.js 16, beginning Aug. 15, 2023. Node.js 16 will reach official end of life on Sept. 11, 2023. Node.js 14 reached official end of life on April 30, 2023.

“On Aug. 15, 2023, Node.js 14 and 16 will be disabled in the Project Settings and existing Projects that have Node.js 14 and 16 selected will render an error whenever a new Deployment is created,” Vercel noted in its announcement. “The same error will show if the Node.js version was configured in the source code.

It added that while existing deployments with Serverless Functions will not be affected, developers should upgrade to Node.js 18 in order to receive security updates.

Microsoft’s TypeScript 5.1 RC Available

Microsoft’s Daniel Rosenwasser, senior program manager of TypeScript, published a detailed look at what’s new in its TypeScript 5.1 release candidate since the beta. Among the changes for developers are:

  • Corrected behavior for init hooks in decorators
  • Changes to emit behavior under isolatedModules, ensuring that script files are not rewritten to modules
  • New refactoring support for moving declarations to existing files

The post also reviews all the changes that 5.1 incorporates now, and Rosenwasser noted that they anticipate very few additional changes before the stable version of TypeScript 5.1 in a few weeks. In fact, the team already recently published the TypeScript 5.2 iteration plan, which will incorporate decorator metadata. Support for decorators is expected to be available in the next JavaScript release.

The post Dev News: New Microsoft Edge Tools and Goodbye Node.js 16 appeared first on The New Stack.

]]>
Dev News: Angular v16, plus Node.js and TypeScript Updates https://thenewstack.io/dev-news-angular-v16-plus-node-js-and-typescript-updates/ Sat, 22 Apr 2023 11:00:43 +0000 https://thenewstack.io/?p=22705998

Angular 16 is due to release in May and it includes support for SSR hydration, writes frontend Principal Software Engineer

The post Dev News: Angular v16, plus Node.js and TypeScript Updates appeared first on The New Stack.

]]>

Angular 16 is due to release in May and it includes support for SSR hydration, writes frontend Principal Software Engineer at F5, Gaurav Mukherjee.

“There are a lot of features/changes coming with this version. Much more than we have seen in any previous major release,” Mukherjee wrote. “Angular is seeing a kind of renaissance, and v16 is just the beginning.”

Among the changes he enumerates are:

  • SSR with hydration, a long sought-after feature. “Without this, lot of developers who wanted to build an end-user-facing application where initial startup time and SEO is very important, withheld from using angular,” he noted.
  • Required input for components. Angular developers have had to use hacks to enforce that inputs are getting passed to the component — unlike in React and other frameworks. “Without this input being passed from the parent, [the] component may not work as intended,” he wrote. “This feature brings this much-requested feature in angular.”
  • ngcc is out, completing the shift to ivy that started in v9. That should reduce Angular bundle side. Angular View Engine libraries can no longer be used after this, which he notes is a “hard break in compatibility.”
  • Binding router information to component inputs, in which some router data will be available in the component directly as input. That means developers won’t have to use Activatedroute to get these specific values, which could remove a lot of boilerplate code from apps, he writes.
  • takeUntilDestroyed and DestroyRef, which he said is another shift Angular is making toward “a more functional approach of writing code.”
  • Signals, “are the new reactive primitive provided by Angular, which will help [the] framework track changes to its model,” he wrote. Some benefits this incurs include simplifying Angular by allowing the reactive primitive to replace rxjs in most cases and reducing app complexity; fine-grained reactivity; and fewer concepts to learn.

Node.js Offers Experimental Feature

Node.js introduced an experimental feature called the Permission Model, according to the feature contributor, software engineer Rafael Gonzaga.

“It allows developers to restrict access to specific resources during program execution, such as file system operations, child process spawning, and worker thread creation,” Gonzaga wrote. “The API exists behind a flag –experimental-permission, which when enabled will restrict access to all available permissions.”

Developers can use the feature to prevent apps from accessing or modifying sensitive data or running potentially harmful code.

Node v20.0.0 includes other changes as well, including custom ESM loader hooks running on a dedicated thread.

import.meta.resolve()


Other changes include an update to the V8 engine to add new features to the JavaScript API; and the Ada url parser.

Using GitHub Actions Adds Security to NPM

Developers can now add a command flag that will publish details of a code’s origin by using GitHub Actions to build software packages for the npm registry, the Register reported Wednesday. That will enhance security, according to the article.

“GitHub Actions is a continuous integration and continuous delivery (CI/CD) platform, which provides a way to automate arcane command line input and software builds,” the Register wrote. “It’s often used by software developers to mechanize the build process for packages distributed through the company’s npm registry, which hosts more than two million of these modular libraries.”

Last week, npm made headlines after three attackers flooded the npm open source package repository for Node.js with bogus packets.

TypeScript 5.1 Beta Released

Microsoft announced the TypeScript 5.1 beta release this week and provided a rundown of the new features.

One feature highlighted is easier implicit returns for undefined-returning functions. Microsoft explained that while JavaScript returns a value as undefined if a function finishes running without hitting a return, previous versions of TypeScript would return as void any functions and returning functions that had no return statements.

“That meant that even if you explicitly said ‘this function returns undefined,’ you were forced to have at least one return statement,” wrote TypeScript Program Manager Daniel Rosenwasser. “This could be a pain if some API expected a function returning undefined — you would need to have either at least one explicit return of undefined or a return statement and an explicit annotation.”

TypeScript 5.1 allows undefined-returning functions to have no return statement. Also, if a function has no return expression and is passed to something expecting a function that returns undefined, it will infer undefined for that function’s return type, the post explained.

To address another similar pain point, under TypeScript’s –noImplicitReturns option, functions returning only undefined now have a similar exception to void, in that not every single code path must end in an explicit return.

Other features in the beta release include:

  • Unrelated Types for Getters and Setters
  • Decoupled Type-Checking Between JSX Elements and JSX Tag Types
  • Namespaced JSX Attributes
  • typeRoots Are Consulted In Module Resolution
  • Linked Cursors for JSX Tags
  • Breaking Changes

Developers can access the beta through NuGet, or through npm with the following command:

npm install -D typescript@beta

The post Dev News: Angular v16, plus Node.js and TypeScript Updates appeared first on The New Stack.

]]>
This Week in Computing: Malware Gone Wild https://thenewstack.io/this-week-in-computing-malware-gone-wild/ Sat, 25 Mar 2023 14:10:18 +0000 https://thenewstack.io/?p=22703513

Malware is sneaky AF. It tries to hide itself and cover up its actions. It detects when it is being

The post This Week in Computing: Malware Gone Wild appeared first on The New Stack.

]]>

Malware is sneaky AF. It tries to hide itself and cover up its actions. It detects when it is being studied in a virtual sandbox, and so it sits still to evade detection. But when it senses a less secure environment — such as an unpatched Windows 7 box — it goes wild, as if possessing a split personality.

In other words, malware can no longer be fully understood simply by studying it in a lab setting, asserted the University of Maryland Associate professor Tudor Dumitras, in a recently posted talk from USENIX‘s last-ever Enigma security and privacy conference.

Today, most malware is examined by examining execution traces that the malicious program generates (“Dynamic Malware Analysis”). This is usually done in a controlled environment, such as a sandbox or virtual machine. Such analysis creates the signatures to describe the behavior of the malicious software.

The malware community, of course, has been long hip to this scrutiny, and has developed an evasion technique known as red pills, which helps malware detect when it is in a controlled environment, and change its behavior accordingly.

As a result, many of the signatures used for commercial malware detection packages may not be able to adequately to identify malware in all circumstances, depending on what traces the signature actually captured.

What we really need, Dumitras said, is execution traces from the wild. Dumitras led a study that collected info on real-world attacks, consisting of over 7.6 million traces from 5.4 million users.

“Sandbox traces can not account for the range of behaviors encountered in the wild.”

They had found that, as Dumitras expected, traces collected in a sandbox rarely capture the full behavior of malware in the wild.

In the case of Wannacry ransom attack, for instance, sandbox tracing only caught 18% of all the actions that the randomware attack executed in the wild.

For the keepers of malware detection engines, Dumitras advised using traces from multiple executions in the wild. He advised using three separate traces, as diminishing returns set in after that.

Full video of the talk here:

Reporter’s Notebook

“So far, having an AI CEO hasn’t had any catastrophic consequences for NetDragon Websoft. In fact, since Yu’s appointment, the company has outperformed Hong Kong’s stock market.” — The Hustle, on replacing CEOs with AI Chatbots.

AI “Latent space embeddings end up being a double-edged sword. They allow the model to efficiently encode and use a large amount of data, but they also cause possible problems where the AI will spit out related but wrong information.” — Geek Culture, on why ChatGPT lies.

“We think someone who writes for a living needs to constantly be thinking about the best way to express complex ideas in their own words.” ⁦– Wired, on its editorial use of generative AI.

“I think with Kubernetes, we did a decent job on the backend. But we did not get developers, not one little bit. That was a missed opportunity to really bring the worlds together in a natural way” — Kubernetes co-founder Craig McLuckie, on how the operations-centric Kubernetes perplexed developers (See: YAML), speaking at a Docker press roundtable this week.

McLuckie also noted that 60% of machine learning workloads now run on Kubernetes.

“After listening to feedback and consulting our community, it’s clear that we made the wrong decision in sunsetting our Free Team plan. Last week we felt our communications were terrible but our policy was sound. It’s now clear that both the communications and the policy were wrong, so we’re reversing course and no longer sunsetting the Free Team plan” —Docker, responding to the outcry in the open source community over the suspension of its free Docker Hub tier for teams.

“Decorators are by far the biggest new feature, making it possible to decorate classes and their members to make them more easily reusable. […] Decorators are just syntactic glue aiming to simplify the definition of higher-order functions” — Software Engineer Sergio De Simone on the release of TypeScript 5.0, in InfoQ.

“If these details cannot be hidden from you, and you need to build a large knowledge base around stuff that does not directly contribute to implementing your program, then choose another platform.” — Hacker News commenter, on the needless complexity that came with using Microsoft Foundation Classes (MFC) for C++ coding.

Now 25 years old, the venerable Unix curl utility can now enjoy an adult beverage in New Dehli.

Ken Thompson “has a long and storied history of trolling the computer industry […] he revealed, during his Turing Award lecture, that he had planted an essentially untraceable back door in the original C compiler… and it was still there.” — Liam Proven, The Register.

“It’s just like planning a dinner. You have to plan ahead and schedule everything so it’s ready when you need it.” —  Grace Hopper, 1967, explaining programming to the female audience of Cosmopolitan.

The post This Week in Computing: Malware Gone Wild appeared first on The New Stack.

]]>
TypeScript 5.0: New Decorators Standard, Smaller npm https://thenewstack.io/typescript-5-0-new-decorators-standard-smaller-npm/ Fri, 24 Mar 2023 18:25:34 +0000 https://thenewstack.io/?p=22703530

TypeScript 5.0 shipped this week, with support for the new decorators standard and a smaller npm footprint than TypeScript 4.9.

The post TypeScript 5.0: New Decorators Standard, Smaller npm appeared first on The New Stack.

]]>

TypeScript 5.0 shipped this week, with support for the new decorators standard and a smaller npm footprint than TypeScript 4.9.

Microsoft’s Daniel Rosenwasser, programmer manager for TypeScript, explained the changes in a blog post, promising that 5.0 “is not a disruptive release, and everything you know is still applicable.” TypeScript 5.0 includes correctness changes and some deprecations for infrequently-used options, he added.

“This release brings many new features, while aiming to make TypeScript smaller, simpler, and faster,” Rosenwasser said. “We’ve implemented the new decorators standard, added functionality to better support ESM projects in Node and bundlers, provided new ways for library authors to control generic inference, expanded our JSDoc functionality, simplified configuration, and made many other improvements.”

Decorators are used in Python, Java and C# and are a stage 3 proposal for JavaScript. Currently, they can be used in JavaScript via Babel and the TypeScript compiler, according to senior software developer Lawrence Eagles. Most browsers do note support decorators presently.

“Decorators, in a nutshell, involve wrapping a piece of code such as a function or a class with another — a decorator function. The aim is to extend the functionality of the wrapped code without modifying it,” wrote Eagles. “Decorators are very powerful and they have a wide range of applications.”

Among the use cases are turning the class method into REST, logging useful information and enabling code reuse, he added.

The new release also offers a smaller typical npm package size, at 37.4 MB compared to 63.8 MB for Typescript 4.9, according to Rosenwasser’s write-up.

TypeScript builds on JavaScript by adding syntax for types that can be used for type-checking, Rosenwasser said. To get started using TypeScript 5.0, you can get it through NuGet, or use npm with the following command:

npm install -D typescript

React.dev Launches New React Home

In other news from the week, React.dev is nearing its 10th birthday. To celebrate, it has launched a new home for the popular library and related documentation. The site teaches modern React with function components and hooks, and features more than 500 new interactive examples and sandboxes.

The previous documentations site is archived at legacy.reactjs.org. The original domain — reactjs.org — will redirect to the new site.

The updated docs teach React with Hooks from the beginning and are divided in two main sections, according to a blog post by developers Dan Abramov and Rachel Nabors:

  • Learn React, a self-paced course that teaches React from scratch and incorporates a “show solution” button for those who get stuck.
  • API Reference, which provides the details and usage examples for every React API. Every API page includes information about reference and usage, with usage showing why and how a developer would use an API in practice.

The new site offers a quick start page for those wanting to learn React, along with an interactive Tic-Tac-Toe tutorial that teaches developers to build a version of the game. It also includes an update to Thinking in React, which Abramov and Nabors said is “the tutorial that made React “click” for many of us.

React remains one of the most popular and widely used JavaScript libraries, according to the 2022 State of JavaScript survey.

Rust Update to 1.68.1

Finally, Rust published a new point release, Rust 1.68.1, on Thursday. Point releases are minor, typically fixing bugs or performing code cleanup. In this case, Rust 1.68.1 contains a change to how Rust’s CI builds the Windows MSVC compiler, no longer enabling LTO for the Rust code.

“This led to a miscompilation that the Rust team is debugging, but in the meantime, we’re reverting the change to enable LTO,” the Rust team stated in a blog post. “This is currently believed to have no effect on the wider usage of ThinLTO. The Rust compiler used an unstable flag as part of the build process to enable ThinLTO despite compiling to a dylib.”

Other regressions fixed in the release:
Fix building the compiler with –enable-local-rust;
Treat $prefix-clang as clang in linker detection code; and
Fix a panic in the compiler.

The post TypeScript 5.0: New Decorators Standard, Smaller npm appeared first on The New Stack.

]]>
JavaScript or WebAssembly: Which Is More Energy Efficient and Faster? https://thenewstack.io/javascript-vs-wasm-which-is-more-energy-efficient-and-faster/ Mon, 30 Jan 2023 17:51:27 +0000 https://thenewstack.io/?p=22699044

Which runs faster and is more energy-efficient: JavaScript or WebAssembly? The University of Minho in Portugal researched this very question

The post JavaScript or WebAssembly: Which Is More Energy Efficient and Faster? appeared first on The New Stack.

]]>

Which runs faster and is more energy-efficient: JavaScript or WebAssembly? The University of Minho in Portugal researched this very question and came to the conclusion that while JavaScript can be more energy efficient and faster than Wasm when it comes to in-lab micro-benchmarks, in real applications Wasm outshines JavaScript on speed and energy efficiency — sometimes by as much as 30% on average.

And that’s with Wasm still in its early days.

“Wasm is still in its infancy and only time could tell us how it will evolve,” study author João De Macedo, a software engineer, told The New Stack via email. “In our wildest predictions, we see Wasm completely pushing out native apps from operating systems and crowning the web browser as the operating system of the twenty-first century.”

Micro-Benchmarks vs. Real-World Applications

The research, published in 2022, looked at real-world benchmarks, as well as micro-benchmarks.

“A micro-benchmark is a program that tracks and measures the performance of a single well-defined task such as elapsed time, rate of operation, bandwidth, etc.,” De Macedo explained. “Micro-benchmarking is one of the principal ways to measure the performance of a software system, thus, Wasm is no exception.

Since one of the main goals of Wasm is to improve the performance of Web applications, it’s “particularly relevant to compare the run-time and energy performance of Wasm and JS,” he added.

When it came to the micro-benchmarks, in some cases JavaScript could be more energy-efficient and faster than Wasm. While Wasm was more energy efficient and outperformed JavaScript on Google Chrome and Microsoft Edge, JavaScript did have better performance results than Wasm on Mozilla Firefox, with a “significant difference most of the time.”

That said, ultimately Wasm still ruled overall in real-world applications.

“Preliminary results show that WebAssembly, while still in its infancy, is starting to already outperform JavaScript, with much more room to grow,” the report stated. “A statistical analysis indicates that WebAssembly produces significant performance differences compared to JavaScript.”

How the JavaScript vs. Wasm Study Worked

The study looked at how well Wasm and JavaScript performed in real-world applications with the Wasmboy benchmark, which is a Gameboy/Gameboy Color Emulator, written in Typescript to benchmark Wasm. Wasmboy is written in JavaScript/TypeScript and it was created with the main goal of comparing the runtime performance between Wasm produced by the AssemblyScript compiler and the ES6 latest version of JavaScript, as produced by the TypeScript compiler.

“This game console includes six different open source games that can be executed by the console,” the report stated. “We updated the WasmBoy source code in order to specify the browser where the games have to be executed.”

So with six games running across three browsers — Chrome, Edge and Firefox — with two languages, the team had a total of 36 unique samples.

They also used the PSPDFKit benchmark, which uses software that supports viewing, annotating, and filling in forms in PDF documents on any platform. The report noted that the open source benchmark was created to assess the possibility of porting the software to the Wasm ecosystem and comparing Wasm to JavaScript implementations. The team made changes to the application’s source code to execute several inputs in the two languages considered (was and asm.js). To execute the benchmark with realistic inputs, the team considered five different pdf documents, including one book divided into three parts, one scientific paper, and a slide presentation of 20 slides.

“Similar to the Wasmboy benchmark, we developed makefiles to automate the execution in the different browsers,” resulting in five samples in each language across three browsers for 30 unique program executions, the report stated.

It also looked at various micro-benchmarks; these programs were originally written in C and compiled into both Wasm and JavaScript using the Emscripten compiler. Other languages that can used to compile to Wasm are C/C++, Rust, Go, Python and AssemblyScript, a form of TypeScript.

Details of the micro-benchmarks and other aspects of the study can be read in “WebAssembly versus JavaScript: Energy and Runtime Performance,” by João De Macedo, Rui Abreu, Rui Pereira, and João Saraiva, which is available with a subscription on the Institute of Electrical and Electronics Engineers.org or for free in De Macedo’s master thesis.

However, the long and short of it is that this approach allowed the team to look at, for instance, how scale and input size were handled differently by JS and Wasm. A previous study had used this approach, but only looked at performance in virtual machines. De Macedo’s study wanted to look at real-world applications, so the team developed a framework to measure performance within a browser-based environment.

Wasm as a JavaScript Replacement?

I asked De Macedo if Wasm will eventually replace JavaScript.

“Maybe never, because JS makes more sense to web pages that don’t need to be ultra-performance,” he responded. “Currently, Wasm serves as a supplement to JS rather than a replacement. However, if Wasm were further developed, it might take the place of JS in some applications because of its faster loading times and more effective resource usage.”

Long-term, De Macedo predicted Wasm will be disruptive.

“Wasm will not only revolutionize the web,” he said. “The promise of WebAssembly has the potential to upend multiple areas of the technology market — including the cloud — which recently has increasingly shifted to a container model that doesn’t always serve every organization’s needs.”

The post JavaScript or WebAssembly: Which Is More Energy Efficient and Faster? appeared first on The New Stack.

]]>
What TypeScript Brings to Node.js https://thenewstack.io/what-typescript-brings-to-node-js/ Mon, 26 Dec 2022 11:00:20 +0000 https://thenewstack.io/?p=22680561

StackOverflow.com ranks computer languages based on the number of questions asked each month. While the Python language has held a

The post What TypeScript Brings to Node.js appeared first on The New Stack.

]]>

StackOverflow.com ranks computer languages based on the number of questions asked each month. While the Python language has held a substantial lead for some time, JavaScript has also maintained a solid second place. This could represent both developer interest and, at some level, familiarity with the nuances of the different languages. Seasoned developers don’t rely on StackOverflow.com to get their job done as much as newbies, but it still comes in handy for quick help.

Understanding the complementary nature of the two technologies requires a definition of terms. Both Node.js and TypeScript have roots firmly planted in JavaScript, which came from the Java language. For the remainder of this article, we will ascribe the term tools to both Node.js and TypeScript, even though you could define TypeScript as a language and Node.js as a platform or a runtime environment.

History of Node.js and TypeScript

Examining the heritage of Node.js and TypeScript requires a bit of a history lesson. Both tools trace their language syntax to Java which James Gosling developed at Sun Microsystems in the mid-1990s. The designers of the Java language envisioned a language that would enable the concept of Write Once Run Anywhere (WORA). This would require a runtime system adapted for each operating system to allow syntax compatibility across various platforms.

The original idea of WORA lives on in the modern Web browser. All popular Web browsers in use today support running JavaScript or TypeScript in the browser. A superset of the JavaScript language, TypeScript employs static type checking to allow consistent use of variables and reduce a potential source of programming errors.

Static Typing

TypeScript brings the concept of static typing to the JavaScript language. Other popular languages incorporating static typing include C, Java, and Rust. Static typing requires variables to have their type consistent after declaration or first usage. The opposite would be a dynamically typed language like Python, which allows variables to change type on the fly. Maintaining type consistency can be verified with a tool like Flow to look for problematic code.

Using TypeScript with Node.js makes it possible to combine the two tools for building server-side applications. The Node.js platform fully supports TypeScript as an option when building your application. For example, the popular JavaScript framework Angular can be used for creating single-page web applications and is written entirely in TypeScript.

Node.js brings so much more to the table than just runtime. The standard installation of Node.js includes the Node Package Manager (NPM) for handling library or module dependencies. It also makes it possible to run code on the server and in the browser. The Node.js ecosystem resembles what you find in the Python community regarding freely available libraries and packages to address a wide range of programming tasks.

Node.js Usage

When you look at how the two tools are used to develop applications, you begin to get a feel for how each fits in the big scheme of things. Node.js has seen significant adoption in the small application space to include things like IoT and tiny devices like Raspberry Pi. TypeScript shines when used for browser-based and user-interface applications.

The acronym NPM represents both a tool and a company. NPM Incorporated was founded in 2014 and acquired by GitHub in 2020. NPM, the device, represents one of the most used pieces of the Node.js package. If you’re looking for some code to perform a specific task, you should start with the NPM website. Type in your requested function in the search bar, and you’ll be presented with several options.

To test this site, we searched for JSON and found 41,920 packages. Results are ranked by popularity, quality, maintenance, or how recently/frequently the package receives updates. Using one of these packages in your project requires a few simple command line instructions.

Node.js and TypeScript Deployment

Deploying applications will vary depending on the target environment. Deploying a Node.js application intended to run locally typically requires you to install the Node.js runtime and supporting tools. Installers for Linux, macOS, and Windows can be downloaded from the main Node.js website. Once the installation program has been completed, you will have access to several Node.js command line tools to build and run your code.

Docker images represent another option available from the Node.js download site. This opens a wide range of possibilities for running your code locally using Docker or a cloud-services provider such as AWS from Amazon or Azure from Microsoft. It’s reasonable to develop an application using TypeScript and Node.js and run it locally or in the cloud.

Wrapup: Node.js and TypeScript

Microsoft created TypeScript to add static typing to the base JavaScript language. Microsoft also has a vested stake in the Node.js world with its acquisition of GitHub, resulting in NPM. Depending on the application you are attempting to build, you could use a combination of both TypeScript and Node.js.

The benefits of using TypeScript for developing enterprise-ready applications far outweigh any potential issues you might encounter.

Looking to hire a Node.js developer? Our friends over at Toptal have some great resources you can check out.

The post What TypeScript Brings to Node.js appeared first on The New Stack.

]]>
Improve your TypeScript Skills with Type Challenges https://thenewstack.io/improve-your-typescript-skills-with-type-challenges/ Fri, 11 Nov 2022 11:00:25 +0000 https://thenewstack.io/?p=22680925

According to the developer’s ABCs, if “C” is code, then “C” is for challenges also. It implies that codes and

The post Improve your TypeScript Skills with Type Challenges appeared first on The New Stack.

]]>

According to the developer’s ABCs, if “C” is code, then “C” is for challenges also. It implies that codes and challenges have a hand-in-hand relationship. It’s likely impossible to find a developer who hasn’t faced challenges while producing utilities and programs. Success in solving a challenge gives them a sense of achievement. The popularity of TypeScript challenges among developers can be attributed to this feeling of victory.

What Is a TypeScript Challenge?

Typescript challenges are problems that can only be solved by understanding the type system in TypeScript. These problems can occasionally become difficult, especially if the developer is a beginner and new to types and TypeScript.

The type-challenge-solution repository offers a location where the developer may obtain answers to those types of problems together with a description of how they were resolved. After reading the explanation, the developer can find a compiled collection of helpful references to delve into further.

To initiate this, the developer may open an issue in the repository. These issues are then labeled as Type Discussion or Dependencies. Other labels associated with the issues are Bug, duplicate, enhancement, invalid, question, won’t fix.

Why Were Typescript Type Challenges Created?

NuxtLabs’ open source developer Anthony Fu created the type challenge.

Typescript challenges make code more predictable and assist developers in finding errors. Correctly writing the code could be tough; for some, understanding Typescript and integrating it can be challenging. An open environment was therefore required to test and practice codes. With the typescript type challenge environment, developers can test a solution before integrating it into the TypeScript project.

An online editor called OJ (Online Judge) system and Playground lets them experiment with Typescript and JavaScript. As the developer enters the syntax, the results are displayed. It is a real-world environment for executing, analyzing, learning, and sharing TypeScript code.

Its utilities let developers test various compiler options and browse through large code samples to understand more about TypeScript’s inner workings. Initially, OJ systems were employed in programming contests.

Developers can advance and completely rewrite type libraries. A type-testing library that has been properly examined for type correctness will help the developer produce high-quality code.

What Is Type <Challenge []>?

The repository’s main objective is to compile and offer interesting Typescript challenges. The maintainability of projects can be enhanced while potential issues are avoided by using high-quality types. Programmers can use this project to write their own utilities, gain a deeper understanding of the type system, or simply enjoy juggling the challenges.

The website tsch.js.org has a collection of Typescript-type challenges with an online judge editor. The system can compile, run, and test submitted programs using built-in data.

The submitted code may be run with limitations, such as time, memory, security, and other restrictions. The system will record and compare the code’s output to the expected output. The result will then be returned by the system.

When errors were discovered in a standard output, the submission was rejected. If there are any bugs in the code, developers must fix them before resubmitting them for review.

Contributors are also attempting to create a community where developers can ask questions and respond to problems they encounter in the real world — they might even be challenging to others.

Developers can already utilize fantastic type utility libraries like ts-toolbelt, utility-types, SimplyTyped, etc., to improve their type-related operations.

  • ts-toolbelt: The well-organized package ts-toolbelt enables developers to carry out sophisticated operations on object types, union types, function types, and literals. It is purpose-built for creating reliable, adaptable, and type-safe software.

With more than 200 utilities, ts-toolbelt is the most comprehensive and well-tested type library currently on the market. Some of the most sophisticated mapping types, conditional types, and recursive types currently available are included in our type collection. You can level up and completely re-code this library.

  • Utility-types: In addition to TypeScript’s built-in mapped types, the repository also contains utility types. Developers don’t have to duplicate them between projects because it offers a set of syntactic Common Types for TypeScript projects supplementary to the existing TypeScript Mapped Types.

To simplify the transition to TypeScript, it also provides a collection of Additional Types compatible with Flow’s Utility Types.

  • Simply Typed: Another Typescript type library for sophisticated types is Simply Typed. This is distinct from others as it strives to be less experimental than others, guided by industry use cases.

Many exposed types appear at the top of built-in functionality in a very thin layer. The objective is to offer all the components required to create brief yet complicated types.

Following is the list of  common challenges that can make a developer’s life easy when mapped with the solutions from the repository

  • Warm-up
  • Easy
  • Medium
  • Hard
  • Extreme

The above are a few examples of common typescript challenges and their solutions. There are other type specifications besides mapping and lookup types, so please check them out and try them yourself here.

The post Improve your TypeScript Skills with Type Challenges appeared first on The New Stack.

]]>
TypeScript on Mars: How HubSpot Brought TypeScript to Its Product Engineers https://thenewstack.io/typescript-on-mars-how-hubspot-brought-typescript-to-its-product-engineers/ Fri, 19 Aug 2022 17:00:20 +0000 https://thenewstack.io/?p=22680846

TypeScript is a wonderful addition to the JavaScript toolbox. Static types mitigate friction as projects scale, and JavaScript projects are

The post TypeScript on Mars: How HubSpot Brought TypeScript to Its Product Engineers appeared first on The New Stack.

]]>

Duncan Walter
Duncan is a senior software engineer on HubSpot’s Frontend Platform team. He works to empower fellow engineers with ergonomic tooling and powerful automation. At HubSpot, he focuses on introducing TypeScript as well as enhancing editor, code mod, code gen and lint tooling.

TypeScript is a wonderful addition to the JavaScript toolbox. Static types mitigate friction as projects scale, and JavaScript projects are scaling fast. Now more than ever, users expect sophisticated and delightful browser experiences that push the limits of available technology. Since 2018, HubSpot’s infrastructure teams have used typed JavaScript to stay ahead of evolving customer expectations, tech debt and the competition at large.

There is a catch, unfortunately. While infrastructure teams like ours benefit from TypeScript, our product engineers have been left behind. Suffice it to say, TypeScript is fundamentally incompatible with the evergreen, “batteries included” tooling our product engineers use and enjoy to build frontend products.

We have high expectations for the infrastructure we provide. Our role is to empower engineers in the happiest, most productive team possible. One of our responsibilities is facilitating access to modern tools like TypeScript. So, we’ve been hard at work knocking down barriers so our engineers can enjoy the excellent TypeScript infrastructure they deserve. This has been an exciting year for our team because our work on TypeScript is finally paying off. HubSpot’s product organization is converting to TypeScript this year.

This migration is an ongoing effort with many facets; building code in TypeScript is only the first step. From an organizational perspective, we’re ramping up our investment in internal TypeScript education and support. On the technical side, we’ve also shipped new tooling for migrating to, editing, and maintaining TypeScript code. Today, we’d like to share some of the problems and solutions we’ve been working on to take TypeScript where it could never go before.

Migrating with Compassion

George Kemp
George is a Senior Software Engineer on HubSpot’s Infrastructure Engineering team. At HubSpot, he’s passionate about building a great developer experience and a solid foundation of tooling. George is passionate about all things JavaScript, but is currently focusing on helping bring TypeScript to HubSpot’s frontend. When not at the keyboard, he is an avid aviation enthusiast and newly minted private pilot. George holds a BS in Mechanical Engineering from the University of Colorado Denver.

This year, our team’s primary focus has been ensuring that our TypeScript migration isn’t disruptive to product engineers. Switching to TypeScript is an impactful change, even under ideal circumstances, and circumstances are often not ideal. For instance, many of our engineers have little to no experience with TypeScript (or any statically typed language). Maintaining team autonomy is another point of concern. Our frontend product teams are dynamic. Some teams may be focused on performance and tooling while others are actively developing new features. We understand that TypeScript migrations won’t be an immediate priority for every team. With that in mind, our approach has been to provide flexible, self-service migration resources. With the right tools in hand, teams can create a TypeScript migration strategy compatible with their mission and available resources. 

Education and support are key given our distributed migration strategy. Working with unfamiliar or poorly documented tooling all day is unsustainably exhausting. It’s imperative that engineers have free access to TypeScript learning materials and control the pace of their own TypeScript adoption. For example, we now provide engineers free access to TypeScript-focused, subscription-based online learning tools in addition to the standard learning benefits all HubSpotters enjoy. Even with access to these resources, learning takes time. Expect and instruct engineers to dedicate work hours to TypeScript learning.

Remember that engineers are often as excited about TypeScript as we are. We cannot overstate how impactful enthusiasm is during a migration. Infrastructure teams’ role typically isn’t advocating for TypeScript. Instead, focus on removing barriers to entry. Every little bit helps. Automate busy work like renaming files and adding types for props using ts-migrate or an equivalent. Configure TypeScript and migrate a single, small file to TypeScript in each project so teams don’t need to worry about configuration steps themselves. Provide tools to identify which modules are ripe for migration or will be the most impactful when migrated. Once.

That said, it’s important to seek out and maintain a healthy dialogue with TypeScript skeptics as well. Both sides of the conversation have much to gain. Skeptics can often pinpoint weak spots in a migration strategy early, which provides valuable extra time for triage and mitigation. Switching seats, it’s vital that engineers know they’re heard and have a say in their tooling. Even if they’ve been outvoted in a general sense, skeptics deserve a compassionate migration process that accommodates their existing workflows and preferences where possible. In our experience, skeptics can even become advocates when their concerns are taken seriously.

Behind the Scenes

On the surface, HubSpotters migrating to TypeScript will see the same behavior they’d expect anywhere else. TypeScript powers editor features, runs during each build and is erased at compile time. But under the hood, our TypeScript infrastructure is unique. Now that we’ve seen HubSpot’s TypeScript migration from a human perspective, I’d like to pull the curtain back to reveal how we achieved this migration at a technical level.

First, some context. HubSpot has opinionated, integrated tooling that abstracts away common engineering needs like local development servers, linter configuration, transpilation, bundling, test automation and deployment. Our tooling is consistently a top reason that engineers love working on our product. Opinionated tooling does come with some maintenance costs, but the value we get in exchange is irreplaceable.

For the purposes of TypeScript support, the key wrinkle in our tooling is that we don’t store dependencies in node_modules. That’s a big deal because TypeScript only knows how to find dependencies if they’re located in node_modules. Also, unlike most other tools in the JavaScript ecosystem, TypeScript intentionally doesn’t support configuring alternate module resolution strategies. Fortunately, when there’s a will, there’s a way. We decided to fork TypeScript. While not a project to tackle lightly, we’ve found it takes a surprisingly small set of changes to support custom resolution strategies in TypeScript.

As previously mentioned, most JavaScript tools support custom resolution strategies, so there’s an abundance of prior art to work with. Almost all of these tools allow users to provide a resolve function. Typically resolve takes a file path and an import specifier, and then returns the path to the requested dependency. This is the heart of any module resolution strategy, and TypeScript is no different under the hood. Step one of patching TypeScript is making resolve configurable. resolve is also the only part of our TypeScript patch which affects type checking, which means it’s the only part of the patch which needs to remain stable over time.

// resolve('.../module.ts', 'react') -&gt; '.../react/index.ts'
 function resolve(fromPath: string, identifier: string): string {
    // return the path of the resolved module specifier
    return '...';
 }

TypeScript needs a couple of other functions to support key editor features like auto imports. First, the opposite of the  resolve function: getModuleIdentifier. In the same way that resolve tells TypeScript where to find a dependency given an import statement, getModuleIdentifier tells TypeScript how to import a dependency given its location. It takes the path of two modules and returns an import specifier. Specifically, it returns the import specifier needed to import the second module from the first. Last, TypeScript needs a getAutoImportableModules function which accepts the path to a project’s root and returns a collection of module path-specifier pairs.

// getModuleIdentifier('.../module.ts', '.../react/index.ts') -&gt; 'react'
 function getModuleIdentifier(fromPath: string, toPath: string): string {
    // return the identifier for referring to toPath from fromPath
    return '...';
 }

 type ImportableModule = {
    path: string;
    identifier?: string;
 };

 function getImportableModules(projectPath: string): ImportableModule[] {
    return [...];
 }

These three functions are drop-in replacements for existing logic within TypeScript. Once they’re made configurable, replace TypeScript’s default logic with the configured version to get up and running with a patched version of TypeScript. This patch is light and generally stable across TypeScript versions, so it can be rebased onto new release branches of TypeScript as they become available.

Looking into the Future

We see many opportunities to augment our existing tools now that TypeScript is in our toolbox. We can bridge the divide between frontend and backend projects with evergreen-generated API types. From there, we’re excited about building new editor features on top of TypeScript’s existing support, analyzing the type health of packages and adding type information to our code mod stack. TypeScript has a bright future at HubSpot. 

The post TypeScript on Mars: How HubSpot Brought TypeScript to Its Product Engineers appeared first on The New Stack.

]]>
PayPal Enhances JavaScript SDK with TypeScript Type Definitions https://thenewstack.io/paypal-enhances-javascript-sdk-with-typescript-type-definitions/ Wed, 17 Aug 2022 19:38:43 +0000 https://thenewstack.io/?p=22681178

Electronic payment giant PayPal has added TypeScript type definitions into its JavaScript SDK, paypal-js npm package. TypeScript types will allow

The post PayPal Enhances JavaScript SDK with TypeScript Type Definitions appeared first on The New Stack.

]]>

Electronic payment giant PayPal has added TypeScript type definitions into its JavaScript SDK, paypal-js npm package.

TypeScript types will allow JavaScript developers to enjoy the same benefits that TypeScript users have, such as detailed type definitions, direct links to documentation, and type hints. With all of this now at their disposal, app developers will be, “much more productive when writing applications,” explained Jamund Ferguson, Paypal developer relations manager, in a recent blog post.

PayPal’s type definitions are available for import together as part of the loadScript() method or individually using the import type functionality. The following post will highlight some of the features of the package and provide insight on how to, “make use of the type definitions to speed up the development of your PayPal applications.”

The package install is the same whether using the loadScript() or import type functionality.

npm install @paypal/paypal-js

Type Definitions with LoadScript

The paypal-js module allows for easy loading of the PayPal JavaScript SDK asynchronously. The process is as follows:

  • The paypal-js module provides the loadScript() method.
  • The loadScript() injects the SDK <script> tag onto the page.
  • When the script tag is injected onto the page, a promise is returned.
  • The promise resolves after the script is loaded successfully.

Tasks such as handing errors and reloading the script when parameters change (currency changes for example) are much easier using this utility.

The image below represents a basic usage example.

TypeScript Hints

In both TypeScript and JavaScript files, TypeScript autocompletion appears as soon as Paypal is typed inside of the loadScript callback. Autocompletion will show all possible priorities on the PayPal namespace (with navigation available for more details on each).

TypeScript type definitions outline what is expected for the input and what the expected return value will be. In the example above, this is seen in the drop-down menu’s highlighted option for the create order button. Just beside it there is a second menu showing exactly what is expected inside of the create order button.

createOrder option takes a callback that can take in two parameters: a Record and CreateOrderActions. The Record is a standard JavaScript object with the key being a string and the value listed as unknown meaning it can be anything. This will return a Promise that holds the order id, a string value. The second parameter, CreateOrderActions is another object.

The IDE will notate an error if anything is missing or typed in incorrectly.

Hovering over the text will provide detailed information about missing arguments and hitting cmd-click on the createOrder method will bring the developer directly to the TypeScript definition.

Opting in to Additional Functionality

Though the JavaScript SDK type definitions are daily comprehensive, the supported methods depend on the components query param passed into the JavaScript SDK <script> tag. Buttons is the only supported method by default. The script configuration guide has more details on selecting necessary components.

TypeScript Definitions without LoadScript

The loadScript() method isn’t required to enable TypeScript definitions in a user’s application. Using the import type syntax rather than the more common import syntax will bypass bringing the dependency into an application and grant access to the benefits of TypeScript at build-time without adding to the bundle size.

Import and import type from the paypal-js module both provide access to the type definitions for the loadScript module and the global window.paypal variable as well.

All types maintained for the PayPal JavaScript SDK are exported directly from the root of the paypal-js module and can be imported individually.

In the example above, both the myIntent and postal_code properties are mistyped prompting a similar error to the one in the image below. This illustrates similarities between type definition functionalities when using the import and import type syntax.

There are dozens of PayPal-related types, each with their own extensive documentation about their properties and purpose, available for use in applications.

The post PayPal Enhances JavaScript SDK with TypeScript Type Definitions appeared first on The New Stack.

]]>
Typescript vs. React.js https://thenewstack.io/typescript-vs-react-js/ Tue, 09 Aug 2022 10:00:45 +0000 https://thenewstack.io/?p=22679913

No matter the sports team, a star player always emerges and receives the most attention. However, no star player can

The post Typescript vs. React.js appeared first on The New Stack.

]]>

No matter the sports team, a star player always emerges and receives the most attention. However, no star player can win games alone. Complementary players set the stage for winning plays. In football, an offensive line allows quarterbacks, running backs, and receivers to gain yardage and score touchdowns. In basketball, the power forward who always gains an important rebound or the defensive-minded guard allows a playmaker to score the game-winning goal.

What is Typescript? Let’s find out.

JavaScript Receives Star Treatment

Star players and complementary players also exist in programming languages — albeit in a different form. We could say — for instance — that JavaScript is a superstar. After all, JavaScript has become the world’s most popular programming language and stakes claim to serve as the programming language of the Web.  Developers use JavaScript to create dynamic and interactive web pages.

As with many star players, JavaScript has a few issues that impact performance and your ability as a developer. Complementary players such as TypeScript and React overcome issues that can lead to errors and offer the tools that enable success with JavaScript.

While dynamic typing gives JavaScript flexibility and agility by delaying the assignment of a type to all variables until the code runs, it also opens the door to errors caused by using variables that have the wrong types for some commands. Even with invalid type arguments or mismatched data, JavaScript blissfully compiles.

Type checking in JavaScript happens at runtime based on the variable’s value at the time. Any detected errors result in an alert that grants the developer an opportunity to fix the code before a crash occurs. Unfortunately, another issue also affects performance. As a weakly-typed language, JavaScript enjoys variable-type agreement freedom. This freedom encourages the type checker to make assumptions about variable types. Assumptions about variable typing can create a cascading effect that begins with misinterpretation, continues without generating an error, and concludes by introducing bugs into production environments.

TypeScript Changes the Game

JavaScript’s roots trace back to client-side and server-side programming.  Yet, as time progressed and applications turned to enterprise-level object-oriented programming, the bulky, complex code of JavaScript could not fit the bill. Microsoft developed the open-source, object-oriented programming language Typescript to change the game. All the good elements of JavaScript incorporate into TypeScript and improved the model to serve enterprise-level needs.

Microsoft’s TypeScript language is the Superset of JavaScript. Any code that runs on Typescript also runs on JavaScript. So…can a Superset of JavaScript also serve in a complementary role?

The answer to this question rests within the use of static typing within TypeScript.  In contrast to the dynamic typing seen with JavaScript, static typing allows programmers to detect errors while typing the code. TypeScript also eliminates the errors associated with the false assumptions that occur with JavaScript. With the type information added to the code, a programmer can also use an Integrated Development Environment (IDE) and the build process to check the types. As a result, all the power contained within JavaScript becomes more efficient… without the risk.

Another key point emphasizes the differences between JavaScript and TypeScript. While JavaScript is weakly typed, TypeScript is strongly typed. As a result, Typescript allows developers to declare variables and data structures as specific and encourages enterprise-wide development with strong typing. TypeScript’s type support enhances the flexibility — and reliability — of JavaScript through interfaces, hybrid types, enums, access modifiers, and other tools.

TypeScript also complements JavaScript by supporting the European Computer Manufacturers Association Script (ECMAScript) 2022 general-purpose programming language standards. The impact of this support becomes apparent through the ability to use the most current ECMAScript features while maintaining compatibility with older features. Developers can use modules, classes, and lambda functions without sacrificing backward compatibility with older versions of JavaScript runtimes.

React Assists JavaScript for Game-Winning Performance

JavaScript allows programmers to change the behavior of web pages. A programmer can create, style, append, and remove elements to change content and achieve interactivity. However, constructing web pages that attract and engage users is only part of the formula needed to win in a new user-interface, mobile-intensive environment. Users seek — and expect — easy access to information and unforgettable web experiences.

Released by Facebook (now Meta) in 2013, React takes interactivity further by providing the tools needed to build superior user interfaces that respond to user input. Like basketball, coaches seek hybrid players that can score, rebound, and play defense, React — or ReactJS — combines native application development with JavaScript user interface development for the Web. In addition, React allows developers to reuse components when creating new applications.

React Native operates similarly to React but provides a hybrid mobile app development framework for mobile applications. While heavy lifting occurs in native modules for iOS and Android, programmers can write code with JavaScript and then share the code across platforms.

Unlike TypeScript, though, React is not a language. Instead, React is a JavaScript Library constructed around predictability, power, and efficiency for building user interfaces. React works with different IDE tool suites that provide a framework of integrated code editors, compilers, debuggers, code libraries, automation tools, and test platforms.

Speed wins. Rather than using the data inputs and outputs in the Document Object Model (DOM), React utilizes the virtual DOM to improve user experiences. While the DOM relies on a server to update possibly thousands of elements in the DOM tree of a document, React uses the virtual DOM to update even the smallest of changes a user applies without impacting the remainder of the interface. With this approach, Reach speeds updates increases performance and facilitate faster programming.

Typescript Versus React: Who Wins?

Friendly competition between players refines skills on the practice field or on the court. Coaches seek the best combination of skills to establish a winning edge when constructing a team. In football, for example, a coach may place an offensive lineman who uses physical size and strength to overwhelm opponents next to another offensive lineman who utilizes technique and intelligence to set a block.

Typescript and React take different paths to complement JavaScript through reliability, flexibility, reusability, and versatility. For just a moment, let’s highlight a few key differences between the two players.

TypeScript Versus React — A Comparison

  • TypeScript is a language.
  • React is a library.
  • TypeScript supports enterprise-wide development.
  • ReactJS and React Native support user interfaces for web and mobile applications.
  • TypeScript utilizes data structures and variables.
  • React uses the virtual DOM.

Although a TypeScript versus React scenario may seem possible, the React framework maintains neutrality by providing an option to use either JavaScript or TypeScript for React applications. Because TypeScript reduces the chances for errors, code libraries become much easier to use.

In addition, the React library supports the type definitions seen with TypeScript and provides data binding. As a result, a developer can track changes made to different data segments. Programmers may also take advantage of the reliability offered through TypeScript when reusing components from one project to the next.

The post Typescript vs. React.js appeared first on The New Stack.

]]>
TypeScript vs. JavaScript https://thenewstack.io/typescript-vs-javascript/ Mon, 08 Aug 2022 10:00:47 +0000 https://thenewstack.io/?p=22679916

There is no simple answer to the decision on the debate of Typescript vs. JavaScript. The answer relies very much

The post TypeScript vs. JavaScript appeared first on The New Stack.

]]>

There is no simple answer to the decision on the debate of Typescript vs. JavaScript. The answer relies very much on your organization’s needs and the personal preference and expertise of the developers/technicians who work directly for you.

When considering Typescript vs. JavaScript, start by looking at your specific organization and use-cases and not some generic comparison table on the web, recommended Adam Abrams, Optimove director of architecture. “For example, we use JavaScript heavily on the frontend and backend, but our backend systems also leverage other technology stacks, mainly .NET and Java. Also, we develop microservices in medium-sized teams (around six developers) and need the ability to maintain the same code by different people on a sprint-by-sprint basis.

Optimove developers are used to typing languages, with a testing methodology that relies on basics such as null references and uninitialized variables, to be handled by the compiler, not by hand by developers, Abrams explained. “That’s why we standardized on Typescript across most of our services. Smaller or one-off services are still developed in JavaScript for speed of doing a POC, or testing a hypothesis. We have already later made the code migration to TypeScript in a gradual fashion for some of those. It’s a painless process (that usually improves the code and uncovers a few hidden bugs.)”

READ RELATED: TypeScript and the Power of a Statically-Typed Language

Abrams added, “The more business logic you put into your code (versus just I/O), the better off you’ll be using TypeScript for self-documenting your code with proper types. In JavaScript, it is easy to mix up units/types and get nonsensical results without notice. We noticed it also enforces good discipline on the developers to use the good parts of JavaScript in the actual code and leave the idiosyncratic parts out.”

Challenges with Typescript and JavaScript

Andrew Pierno, Veritone’s director of engineering, sees challenges with either answer in the TypeScript vs. JavaScript debate.

JavaScript is confusing, frustrating, seemingly easy to get started with, and impossible to master, Pierno explained. It is so flexible it’s easy to tie yourself in a knot. There are a million ways to do things, new tools coming out every day, and for as long as it’s been around has been the ugly stepchild of programming languages.

According to Pierno, a JavaScript advantage is that it is readily available for uses from web apps to desktop apps and even for blockchain-related uses. TypeScript solves the issue of JavaScript having “weird” types.

“But in my experience, that’s not an actual problem,” Pierno said. “Not once have I had a production system go down because of a TypeScript problem. TypeScript is two times the work to solve a problem I’ve never seen nor had. TypeScript offers the comfort of a strongly typed language for people coming from other programming languages. You can bolt it on to most applications and introduce it piece-meal in the most critical parts of the application.”

Typescript adds additional protection for large teams by introducing bugs that a compiler would normally catch in other languages but wouldn’t be caught without TypeScript in vanilla JavaScript, according to Pierno.

Minor Differences between TypeScript and JavaScript

“If you’re already using application frameworks or components or working with existing code based on JavaScript, converting to TypeScript will likely involve a major lift, particularly if your developers and support people have expertise in JavaScript and not TypeScript,” according to Jacob Ansari, Schellman security advocate, and emerging cyber trends analyst. With no compelling winner in the Typescript vs. JavaScript discussion, any situational benefits you might accrue from switching languages will likely come with a big cost in terms of testing functionality and retraining people.

“My suspicion is that making a move like that on an existing codebase for security reasons is rarely worth it, unless you suddenly get a new development team who has a lot of expertise in the new language and hates the old,” Ansari added. “Most organizations are better off fully understanding the security tradeoffs their languages, toolsets, and technologies provide and make design and implementation decisions based on those factors. better for its needs (and why)?”

The Case for TypeScript

Despite Ansari’s case for staying with whatever you are using now, Carl Saunders, co-founder and full stack developer for Raven Code Limited, argues that TypeScript is the clear winner in this debate.

“TypeScript is the only one you should use, as it transcompiles down to JavaScript,” Saunder said. “You don’t even have to write TypeScript in most cases — modern editors such as Visual Studio Code and WebStorm will infer the types (integrate with TypeScript) out of the box. This comes with huge benefits, as IntelliSense support will autocomplete the code and even highlight when a developer is doing something wrong (type checking). This alone will stop most errors being committed to the codebase before a review of the code is carried out.”

With TypeScript, a developer can easily write clean and maintainable code, allowing them to concentrate on writing the feature, Saunders said. Another benefit of TypeScript is a developer can adopt early ECMAScript specification proposals before they are publicly available, and behind the scenes, TypeScript will polyfill those features.

“TypeScript can also be used as a command line interface (CLI),” Saunders added. “This means a developer can run it as part of the developer workflow and within a background task. More importantly, it can be executed as part of the continuous integration (CI) build pipeline. This allows errors to be caught even before the code is ever deployed to users.”

Which One Should You Use?

It’s clear the choice for Typescript vs. JavaScript will come down to if you are already using one or the other and are comfortable with it. If so, look through the discussion above to see if there is any compelling reason to switch.

If starting from scratch, you’ll want to read through the discussion above, experiment a little, and see which appears to be a better fit for your organization.

The post TypeScript vs. JavaScript appeared first on The New Stack.

]]>
What Trivago Learned Adopting TypeScript https://thenewstack.io/what-trivago-learned-adopting-typescript/ Wed, 03 Aug 2022 17:00:07 +0000 https://thenewstack.io/?p=22679723

Recently, the hotel search company Trivago migrated its core website, along with over 50 other Trivago domains, from PHP/ JavaScript

The post What Trivago Learned Adopting TypeScript appeared first on The New Stack.

]]>

Recently, the hotel search company Trivago migrated its core website, along with over 50 other Trivago domains, from PHP/ JavaScript to TypeScript. The final version of this mid-to-large scale project includes 200,000 lines of code spread across 2,600 .ts files and 115,000 lines of code spread across 1,500 .tsx files.

Tom Bartel, Trivago team lead interface for the platform, explained in a recent blog post that most of the developers on the team didn’t have a lot of experience with TypeScript. But, for the migration, every imaginable detail was heavily considered so it made sense that the programming language would be evaluated as well.

There’s a learning curve when moving from JavaScript to TypeScript and it does slow down the average pace of code writing, he wrote. Some of that slowdown, the time dedicated to thinking about the flow of data moving through the application, is well worth it in the long run. Bartel explained that it, “sharpens your thinking and increases your discipline.” Defining the types correctly is almost half of the battle.

Love at Second Sight

Before starting to code with TypeScript, the engineers, even those with more limited experience went in with an open mind and some education. Nonetheless, the developers initially found that it was easy to get frustrated. The code below illustrates the highly functional style of JavaScript code (including a lot of map, reduce, and currying) often used before the migration. You see there is more ease in passing arguments from one function to another when the data shape isn’t explicitly defined.

This type of code comes with many additional challenges in TypeScript as the type definitions need to be correct. The options here are either to put much effort into getting the types right (which likely means heavy use of generics) or change the coding style to something less functional.

Even if every detail of the code isn’t understood 100%, as long as the types are correct,  it’s likely that the code will work properly.

Once the adaptation process was finished, Trivago’s engineers found that “TypeScript gives you a lot of confidence in your code,” explained Bartel. While this is a plus when writing new code, there is an extra value when working on code that already exists. Bartel added the tip of even if every detail of the code isn’t understood 100%, as long as the types are correct,  it’s likely that the code will work properly.

Now that the rewrite has come to a close, Bartel shares that it feels strange for anyone from the team to work in a non-TypeScript code base. He asked the question, “how do you even reason about the code without knowing what’s in this variable, or if this parameter can ever be null?”

Rely on Your (GraphQL) Schema Types

Trivago auto-generated TypeScript type definitions by leveraging the GraphQL schemas they were already using in their legacy code. The command apollo client:codegen contacted the GraphQL server and updated the client-side types:

GraphQL types is the package where Trivago writes the auto-generated code; they isolate it from the hand-written code as a precautionary measure to keep the files conflict-free.

The code below illustrates the auto-generated files and that the interface names are “not pretty,” Bartle admitted.

Trivago exports them under different names which can be seen in the example below.

The example below is one of two best practices. This has worked well for Trivago. The second of the two best practices is to connect the application type system to the automatically generated schema types.

Insight: Prefer ‘Connected’ Types Wherever Possible

Here we discuss the pros, cons, and ins and outs of type casting. For Trivago, data modeling and the creation of types in TypeScript was expected and, as a general concept, unproblematic. The challenge and solution Bartel discussed is the introduction of hand-written types of core entities that are also part of the schema. Some of the core entities in Trivago’s application are Accommodation, Price, etc.

The code below shows the incorrect way to type cast as they were just type casting one into the other:

The correct way to type cast is as follows:

By type casting this as an object, its deals field is also type casted even though the deals field coming from the server has a slightly different type.  This “mostly worked” as the hand-written types were “rather similar” to the auto-generated ones but in the end, this can be a “recipe for disaster because you fool yourself and prevent TypeScript from spotting bugs for you,” says Bartel.

Two common problems missed during type casting are:

  • Missing Fields: This takes place when the hand-written type as a field that doesn’t exist in the schema. Developers will tryst that a field is there when this is impossible as the server doesn’t deliver it.
  • Null/ non-null: This happens when the server delivers a null value but the hand-written type says a field is set.

Both problems are similar in that TypeScript says a field is there, but in reality, it’s undefined or null, leading to bugs that Bartel described as, “Nasty and very unexpected runtime errors.” Manual testing is the only way it would be caught and that’s really only by luck as it’s challenging to test for specifically and automatic testing most likely will not catch it as those tests would also have to circumvent type safety with a similar type cast which Bartel explained is rather unlikely. This kind of bug, unfortunately, is one that hits in production.

Conclusion

Bartel recommended TypeScript for new projects and libraries. He also recommends it for existing projects due to the ability to migrate gradually. He believes, “the benefits will soon outweigh the initial adaptation problems.”

The post What Trivago Learned Adopting TypeScript appeared first on The New Stack.

]]>
TypeScript Tutorial: Go beyond ‘Hello, World!’ https://thenewstack.io/typescript-tutorial-go-beyond-hello-world/ Sun, 31 Jul 2022 10:00:41 +0000 https://thenewstack.io/?p=22679427

Last week, I posted an introductory piece about TypeScript (“TypeScript Tutorial: A Guide to Using the Programming Language“) where I

The post TypeScript Tutorial: Go beyond ‘Hello, World!’ appeared first on The New Stack.

]]>

Last week, I posted an introductory piece about TypeScript (“TypeScript Tutorial: A Guide to Using the Programming Language“) where I not only introduced you to the language but walked you through creating your first application. Said application was the ubiquitous “Hello, World!” which does one thing — print out the phrase “Hello, World!” in the terminal.

That’s awesome… but only serves to help you take your first steps with the language. Of course, TypeScript can do much more than just print out “Hello, World!” and I want to help you take those next important steps.

In case you didn’t already read the first piece, make sure you do as that will not only walk you through the “Hello, World!” app, it also demonstrates how to install TypeScript on the Linux platform with the help of Node.js and npm. So, before you continue reading this, make sure to get TypeScript installed and read about the “Hello, World!” app creation.

Done and done.

Let’s move on.

Expanding the ‘Hello, World!’ App

And you thought you were done with that little app. Never. What were going to do is highlight one of TypeScript’s cool features which enables it to print the message into a web browser.  In the first piece, we built the app which generated the hw.js file. If we run that app with the command node hw.js, we’d see the correct output of Hello, New Stack! (threw you for a loop there).

But what if we wanted to print that output in a web browser? We can do that and it’s pretty simple. Let’s walk through it.

First, change into the directory you created the new project in. From the original piece, that directory is named “helloworld”, so change into with:

cd ~/helloworld

You should see two files: hw.js and hw.ts. The hw.ts file is where we built the app and hw.js is the JavaScript file generated from the code, using the tsc hw.ts command.

What we’ll do now is create a basic HTML index file that calls the hw.js application and prints the output in a web browser. Because TypeScript is a superset of JavaScript, you might find this usage to be pretty familiar (if you’ve ever worked with JavaScript).

The first thing we’ll do is create an index.html file with the command:

nano index.html

We’ll add the usual HTML elements to this file to start. So, copy/paste the following (or craft your own basic index file) into the new file:

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="UTF-8"&gt;
&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
&lt;title&gt;TypeScript: Hello, New Stack!&lt;/title&gt;
&lt;/head&gt;


With the head section done, let’s focus on the body. What we’re going to do is use the script src call to point to the hw.js JavaScript file. That section looks like this:

&lt;body&gt;
    &lt;script src="/home/jack/helloworld/hw.js"&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;


Notice, in the above section, I have the explicit path to the hw.js file. If you were to add ~/helloworld/hw.js, the app would have problems. Because of that, you want to make sure to type out the full path to the JavaScript application.

Save and close the file.

Now, open that file with your default web browser and it should print out Hello, New Stack! (Figure 1).

Figure 1: Success! Our app was able to output to the browser.

Now, let’s get beyond “Hello, World!”.

Adding Numbers with TypeScript

Let’s use TypeScript to add two numbers together. This will demonstrate not only how to use variables with the language but also how to use the add function.

Create a new ts file with:

nano numbers.ts

The first line of the app will call the add function and looks like this:

function add(x, y) {


We end that line with a brace because we’re not finished with this section. We need to then add:

return x + y;
}


The entire first section defines our function that will add the values of x and y that we’ll define in the next line that looks like this:

var sum = add(3.14, 10);


The above line adds our x (3.14) to our y (10) but doesn’t do anything else. We then need to print out the value we’ve assigned to the sum variable with the line:

console.log(sum);


Our entire application looks like this:

unction add(x:number, y:number) {
        return x+y;
}

let sum = add(3.14,10);
console.log(sum);


You’re on fire!

Save and close the file. Next, we’ll compile that into JavaScript with:

tsc numbers.ts

That will create the numbers.js file, which we can run with:

node numbers.js

The results of running the app will print out 13.14 (because we added 3.14 to 10).

Okay, this is great. What about taking input from a user? That’s possible as well, using the parseInt function. Let’s create a simple application that asks the user for their name and prints it out. Before we do this, we need to install type definitions for Node.js with:

npm i --save-dev @types/node

After taking care of that, create the new file with:

nano name.ts

In that file, paste the following:

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

readline.question('What is your name?', name =&gt; {
  console.log(`Hello, ${name}!`);
  readline.close();
});


In the above code we:

  • Set the const variable readline to accept input from the user with the createInterface function.
  • Print out the question “Who are you? and assign the input to the variable name.
  • Print out whatever was assigned to name.

Save and close the file. Compile the app into JavaScript with:

tsc name.tc

Now, run the app with:

node name.js

You’ll be asked for your name and the app will then print the name out in the console.

And there you have it! Your next steps with the TypeScript language. To dive further into this fantastic language, make sure to visit the official TypeScript documentation.

The post TypeScript Tutorial: Go beyond ‘Hello, World!’ appeared first on The New Stack.

]]>
What Is TypeScript? https://thenewstack.io/what-is-typescript/ Tue, 26 Jul 2022 13:00:41 +0000 https://thenewstack.io/?p=22678983

TypeScript is a programming language heavily built on top of JavaScript. But what makes TypeScript a language users can trust?

The post What Is TypeScript? appeared first on The New Stack.

]]>

TypeScript is a programming language heavily built on top of JavaScript. But what makes TypeScript a language users can trust?

Let’s dive deeper into what TypeScript is and what it can do for JavaScript users.

Understanding TypeScript

TypeScript is a strongly typed, object-oriented, compiled programming language that builds on JavaScript. It is a superset of the JavaScript language, designed to give you better tooling at any scale.

The lead architect behind TypeScript is Anders Hejlsberg, designer of C# at Microsoft. TypeScript is open source, backed by Microsoft, and considered both a language and a set of tools.

TypeScript calls itself “JavaScript with syntax for types.” In short, it is JavaScript with some additional features.

Components of TypeScript

TypeScript comprises three main components: Language, the TypeScript Compiler, and the TypeScript Language Service.

  1. Language: the syntax, keywords, and type annotations.
  2. The TypeScript Compiler (TSC): converts the instructions written in TypeScript to its JavaScript equivalent.
  3. The TypeScript Language Service: an additional layer of editor-like applications, such as statement completion, signature help, code formatting, and colorization, among other things.

What TypeScript Does

TypeScript is often considered “JavaScript and more.” More precisely, there are four main goals of TypeScript:

  1. Make JavaScript development more efficient
  2. Introduce optional types to JavaScript
  3. Help catch mistakes earlier
  4. Implement planned features of future JavaScript

The Gaps in JavaScript

JavaScript is a loosely typed programming language developed by ECMA’s Technical Committee 39. In many ways, JavaScript is a universal language of the web, with multiple vendors supporting different implementations, e.g., Google, Microsoft, Oracle, etc.

To understand TypeScript’s relation to JavaScript, one must remember that JavaScript was originally introduced as the language for the client side. But with the development of Node.js, JavaScript is now also being identified as an emerging server-side technology.

This is where complications begin to arise.

As JavaScript grows, it is getting more complicated, making it difficult for users to keep things tidy as they maintain and reuse the code.

But this isn’t the only roadblock inhibiting JavaScript’s development as a server-side technology.

By neglecting new features like strong type checking, compile-time error checks, and object orientation, JavaScript is preventing itself from becoming a fully-fledged server-side technology — which it must become if it ever succeeds at the enterprise level.

Separately, JavaScript remains a loosely typed language, which can be inhibiting in and of itself. With function parameters and variables offering little to no information, developers are often left fumbling in the dark trying to determine what types of data are being passed where in JavaScript. They either have to waste time looking at the documentation or — in worst cases — simply do their best to guess based on the implementation.

How TypeScript Fills in JavaScript’s Gaps

As a strongly typed programming language that builds on JavaScript, TypeScript’s mission is to step in and fill these gaps to enable application-scale development better.

Enhanced IDE Support

As a whole, TypeScript greatly enhances the development experience for JavaScript users.

In many ways, this is largely due to the improved IDE (integrated development environment) support brought by TypeScript, where the TypeScript compiler informs the IDE on rich type information in real-time.

This facilitates several advantages for the user.

For one, it’s easier to catch errors. While coding, compilation errors are identified with a red line directly in the IDE. And when you have questions about what functions a library might offer, you can get inline help, thanks to code completion. This streamlines workflow, as you no longer need to stop and seek help from external, online references.

Together, this enhanced IDE support boosts overall user productivity.

Static Typing and Type Inference

JavaScript is dynamically typed. In other words, until a variable is instantiated at runtime, JavaScript cannot know what type it is.

But in some scenarios, this may be too late. And if a variable is falsely assumed to be a certain type, this can cause significant bugs.

This is another area where TypeScript adds support for the loosely typed JavaScript.

With TLS (the TypeScript Language Service mentioned above), TypeScript has an optional static typing and type inference system that can infer undeclared variables. Thus, by adding type support to JavaScript, TypeScript can effectively mitigate type errors during compilation to JavaScript.

Compilation

Again, one of the biggest drawbacks of JavaScript is that it is difficult to find and rectify errors.

This is partly due to the fact that JavaScript is an interpreted language and, thus, must be run to test that it’s valid. And in the case that there is an error, users are often left on a wild goose chase to find the bugs in the code.

TypeScript helps make error checking easier.

As TypeScript compiles the code, it will identify syntax errors and notify users by generating compilation errors. Thus, TypeScript helps users catch bugs at the compile time instead of waiting until runtime.

ECMAScript Features

While the JavaScript language is standardized through the ECMAScript standards, not all browsers and JavaScript runtimes support all ECMAScript standards.

This is where TypeScript steps in to make the difference, helping users access the future of JavaScript — today. Because with TypeScript, developers can use many of the latest ECMAScript features (e.g., modules, lambda functions, classes, the spreader operator, and destructing) even before web browsers or other environments fully support them.

Moreover, the language allows users to translate ECMAScript features to older ECMAScript targets of their choosing. This gives the ability to safely use new features while always having the assurance to remain backward compatible with older browsers and JavaScript runtimes.

Object Oriented Programming

Finally, unlike JavaScript, which has yet failed to embrace object-oriented programming, TypeScript supports object-oriented programming concepts in the vein of classes, interfaces, and inheritance.

TypeScript Competitors

Of course, other languages compile to JavaScript, of which CoffeeScript and Dart are the most popular. However, TypeScript consistently stands out among these competitors.

For example, CoffeeScript is a lightweight language that aims to simplify JavaScript. But what it gains in readability for users, it loses in deep readability for tools, as it lacks the optional static typing afforded by TypeScript.

Dart, meanwhile, while also a typed superset of JavaScript, is more akin to a full replacement for the language.

However, most challenging for these competitors is their interoperability with JavaScript; as Dart and Coffeescript are relatively new languages, extension to JavaScript requires more language-specific execution. TypeScript, on the other hand, is distinct in its superiority in extending to JavaScript.

Why Use TypeScript?

TypeScript builds on JavaScript to effectively fill in the gaps and give developers better tooling at any scale. Weighed against its competitors, TypeScript is both easier and more efficient.

Ease of Use

One of the chief advantages of TypeScript is its ease of use. If you are at least a little familiar with JavaScript, it will require very little effort to get started with TypeScript. This is because all TypeScript code is converted into its JavaScript code equivalent for execution.

Conversely, any JavaScript (.js) file can be renamed to a TypeScript (.ts) file for compilation with other TypeScript files.

Portability

In many ways, TypeScript is JavaScript, i.e., TypeScript code converts to JavaScript to run anywhere JavaScript runs. Consequently, users can have confidence that TypeScript can run on any environment that JavaScript runs on — browsers, devices, and operating systems.

This starkly contrasts with many TypeScript competitors that require a dedicated VM or specific runtime environments for execution.

Robust Developer Tooling Support

Overall, TypeScript aims to improve developers’ efficiency and productivity by mitigating errors, aiding problem-solving, and delivering better tooling at scale.

TSC is also advantageous for developers because it can run as a background process to support compilation and IDE integration.

How to Get Started with TypeScript

To get started using TypeScript, the best approach is gradual adoption.

This means incrementally applying types to your JavaScript to improve your codebase and editor support, step by step.

The most common way to use TypeScript is to use TSC:

  1. Write the TypeScript code.
  2. Then, use TSC to compile the TypeScript code into plain JavaScript code.
  3. Finally, deploy the JavaScript code to any environment that runs JavaScript.

If you want to get more into the nuts and bolts of TypeScript, check out this comprehensive TypeScript tutorial.

The post What Is TypeScript? appeared first on The New Stack.

]]>
TypeScript Tutorial: A Guide to Using the Programming Language https://thenewstack.io/typescript-tutorial-a-guide-to-using-the-programming-language/ Sun, 24 Jul 2022 10:00:31 +0000 https://thenewstack.io/?p=22678690

JavaScript is one of the most widely-used programming languages for frontend web development on the planet. Developed by Microsoft, TypeScript

The post TypeScript Tutorial: A Guide to Using the Programming Language appeared first on The New Stack.

]]>

JavaScript is one of the most widely-used programming languages for frontend web development on the planet. Developed by Microsoft, TypeScript serves as a strict syntactical superset of JavaScript that aims to extend the language, make it more user-friendly, and apply to modern development. TypeScript is an open source language and can be used on nearly any platform (Linux, macOS, and Windows).

TypeScript is an object-oriented language that includes features like class, interface, Arrow functions, ambient declaration, and class inheritance. Some of the advantages of using TypeScript include:

  • Runs on any browser or JavaScript engine.
  • Uses the same syntax as JavaScript and all TypeScript code is converted into JavaScript.
  • TypeScript code can be called from existing JavaScript code.
  • Works with existing JavaScript frameworks.
  • Provides support for JavaScript libraries.
  • Supports the latest JavaScript features.
  • Easy integration with third-party tools.
  • Fewer runtime errors.
  • Better code quality and documentation

Some of the features that TypeScript offers over JavaScript include:

  • Optional static typing
  • Readability
  • Vast IDE Support
  • Object-Oriented Programming
  • Support for the latest ECMAScript features

One of the biggest advantages of using TypeScript is that it offers a robust environment to help you spot errors in your code as you type. This feature can dramatically cut down on testing and debugging time, which means you can deliver working code faster.

Ultimately, TypeScript is best used to build and manage large-scale JavaScript projects. It is neither a frontend nor backend language, but a means to extend the feature set of JavaScript.

I’m going to walk you through the installation of TypeScript and get you started by creating a very basic Hello, World! application.

Installing TypeScript and VSCode on Linux

Let’s get TypeScript installed on Linux (specifically, Ubuntu 22.04). In order to do this, we must first install Node.js. Log into your Ubuntu Desktop instance, open a terminal window and install both Node.js and npm with the command:

sudo apt-get install nodejs npm -y

With Node.js and npm installed, we can now install TypeScript with npm using the command:

npm install -g typescript

If that errors out, you might have to run the above command with sudo privileges like so:

sudo npm install -g typescript

To verify if the installation was successful, issue the command:

tsc -v

You should see the version number of TypeScript that was installed, such as:

Version 4.7.4

Now that you have TypeScript installed, let’s add an IDE into the mix. We’ll install VSCode (because it has TypeScript support built-in). For this we can use Snap like so:

sudo snap install code --classic

Once the installation is complete, you can fire up VSCode from your desktop menu.

Create your Hello, World! app

The first thing we’re going to do is create a folder to house our Hello, World! application. On your Linux machine, open a terminal window and issue the command:

mkdir helloworld

Change into that directory with:

cd helloworld

Next, we’ll create the app file with:

nano hw.ts

In that new file, add the first line of the app like so:

let message: string = 'Hello, New Stack!';


Above you see we use let which is similar to the var variable declaration but avoids some of the more common gotchas found in JavaScript (such as variable capturing, strange scoping rules, etc.). In our example, we set the variable message to a string that reads Hello, New Stack!. Pretty simple.

The second line for our Hello, World! app looks like this:

console.log(message);


What this does is print out to the console log whatever the variable message has been set to (in our case, Hello, New Stack!).

Our entire app will look like this:

let message: string = 'Hello, New Stack!';
console.log(message);<i>
</i>


Save and close the file.

With VSCode open, click Terminal > New Terminal, which will open a terminal in the bottom half of the window (Figure 1).

Figure 1: We've opened a new terminal within VSCode.

Figure 1: We’ve opened a new terminal within VSCode.

At the terminal, change into the helloworld folder with the command:

cd helloworld

Next, we’ll generate a JavaSript file from our TypeScript file with the command:

tsc hw.ts

Open the VSCode Explorer and you should see both hw.js and hw.ts (Figure 2).

Figure 2: Both of our files as shown in the VSCode Explorer.

Select hw.js and then click Run > Run Without Debugging. When prompted (Figure 3), select node.js as your debugger.

Figure 3: Selecting the correct debugger is a crucial step.

Figure 3: Selecting the correct debugger is a crucial step.

Once you do that, VSCode will do its thing and output the results of the run (Figure 4).

Figure 4: Our Hello, World! app run was a success.

Figure 4: Our Hello, World! app run was a success.

What if you want to do all of this from the terminal window (and not use an IDE)? That’s even easier. Go back to the same terminal you used to write the Hello, World! app and make sure you’re still in the helloworld directory. You should still see both the TypeScript and JavaScript files.

To run the Hello, World! app from the command line, you use node like so:

node hw.js

The output should be:

Hello, New Stack!

Congratulations, you’ve installed TypeScript and written your first application with the language. Next time around we’ll go a bit more in-depth with what you can do with the language.

The post TypeScript Tutorial: A Guide to Using the Programming Language appeared first on The New Stack.

]]>
TypeScript and the Power of a Statically-Typed Language https://thenewstack.io/typescript-and-the-power-of-a-statically-typed-language/ Tue, 08 Feb 2022 21:36:14 +0000 https://thenewstack.io/?p=21190509

If there is a secret to the success of TypeScript, it is in the type checking, ensuring that the data

The post TypeScript and the Power of a Statically-Typed Language appeared first on The New Stack.

]]>

If there is a secret to the success of TypeScript, it is in the type checking, ensuring that the data flowing through the program is of the correct kind of data. Type checking cuts down on errors, sets the stage for better tooling, and allows developers to map their programs at a higher level. And TypeScript itself, a statically-typed superset of JavaScript, ensures that an army of JavaScript programmers can easily enjoy these advanced programming benefits with a minimal learning curve.

In this latest edition of The New Stack Makers podcast, we spoke with a few of TypeScript’s designers and maintainers to learn a bit more about the design of the language: Ryan Cavanaugh, a principal software engineering manager for Microsoft; Luke Hoban, chief technology officer for Pulumi, who was one of the original creators of TypeScript, and; Daniel Rosenwasser, senior program manager, Microsoft. TNS editors Darryl Taft and Joab Jackson hosted the discussion.

TypeScript and the Power of a Statically-Typed Language

TypeScript came about within Microsoft in 2012 as a way to help their  C++ or C# developers to write large-scale web applications, recalled Hoban, who was then part of the developer tools group at Microsoft.

The natural choice was to use JavaScript, the dominant language for the web. But JavaScript didn’t offer much tooling to help developers organize, assist and check their code writing. Various early solutions worked on by Microsoft and other web-scale companies were mostly efforts to compile traditional languages such as C++ into JavaScript, though this left developers at “an arm’s length from the platform,” Hoban said.

They wanted to develop a language that had the “ability to express types into the syntax as a lightweight extension to JavaScript, but …  still offer as much sort of inference as possible, so that you need to use those annotations sort of as infrequently as possible,” Hoban said.

The answer came in making a superset of JavaScript that would be fully compatible with JavaScript and can be transpiled into JavaScript for full browser compatibility. To add rigor, it came with additional type checking. But it would be a nuanced form of type checking that wasn’t too painful to the developer.

The developers of the project are proud of the flexibility that TypeScript offers. Simply mandating that the developer assign a previously-defined type to each variable would be overkill, they admitted. A developer may want to do something tricky, like create a function that makes identical copies of an object, but with the property names all in lower case. The type system had to support this complexity.

“We have a lot of expressivity in our type system,” Cavanaugh said. “We built up many constructs over time in the type system to the point where when you create a type, you’re actually kind of running it through a mini programming language within our type system.”

The development team hopes to have recently implemented recursive typing, where a custom type may be a set number of programming rules.

“We’re trying to enable the right patterns where you’re actually able to express what your JavaScript is doing at runtime. We don’t want people to go overboard, but we’re trying not to like get them stuck in some cases,” Cavanaugh said.

TypeScript now implements a control flow-based type analysis for local variables and parameters. For this, the design team conducted code flow analysis to better understand how data types were being used so TypeScript “just kind of automagically picks up how the types are flowing through your program, so you’re just really writing JavaScript at the end of the day,” Cavanaugh said. (Despite the benefits of type checking, it may be a while if it ever finds itself into JavaScript itself, our panelists agreed. Basic type checking would be easy enough for the browser, but the most complex evaluations would be difficult to implement in runtime. )

With TypeScript, developers are able to map out their programs at a much larger scale, in a way that makes sense to others joining the project later on. “So you’re starting to see much richer and more complex applications which would not have been possible otherwise,” Cavanaugh noted. TypeScript is used across Microsoft for most of all of its web applications, for instance. It is a favorite among JavaScript framework developers, including Angular.js. Slack used Typescript to build its desktop client. It is an integral part of Figma, a popular open source web design tool.

But it can also be used for smaller projects as well. Rosenwasser recalled writing a small script for a one-time project. Initially, he chose JavaScript so he didn’t have to go through the transpiler step. He got caught up trying to find an elusive bug, however. He ran the code through the TypeScript ts-check tool and immediately found the error.

The typing also helps with security. Built for a hostile web environment, JavaScript already has good built-in security, with built-in memory security and a bevy of runtime checks. Where Typescript helps is that it shows and prevents higher-level logic errors, especially those that can come from incorrectly handling input data.

“Data corruption can lead to a security problem. And making sure that you’re like always calling things the right way is just as part of that,” Cavanaugh said.

The post TypeScript and the Power of a Statically-Typed Language appeared first on The New Stack.

]]>