express template typescript in javascript

In TypeScript, we can define a generic type using <> syntax. For example, a simple Identity function that returns the same value it receives would look like this:

index.ts
function identity<T>(arg: T): T {
    return arg;
}
52 chars
4 lines

To express this in plain JavaScript, we can use template literals, which allow us to define a string with placeholders that can be replaced at runtime:

index.tsx
function identity(arg) {
    return arg;
}
43 chars
4 lines

The T type parameter is no longer necessary, as JavaScript is a dynamically-typed language. If we want to restrict the type of the argument to a specific interface, we can do this:

index.ts
interface HasName {
    name: string;
}

function sayHello<T extends HasName>(obj: T): string {
    return `Hello, ${obj.name}!`;
}
132 chars
8 lines

In JavaScript, we can achieve the same effect using plain object arguments and template literals:

index.tsx
function sayHello(obj) {
    return `Hello, ${obj.name}!`;
}
61 chars
4 lines

Note that we don't have a way to enforce the HasName interface in JavaScript, but we can still use it as a documentation tool.

gistlibby LogSnag