how to use the template function from the underscore library in typescript

The underscore library provides a template function that is useful for generating strings that contain interpolated values. Since the function takes a string and an object containing values to interpolate, it can benefit greatly from typing in TypeScript.

To use the template function in TypeScript, we should start by installing the library as a dependency:

index.ts
npm install underscore
23 chars
2 lines

Then, we can import the template function and define its type signature. Here is an example:

index.ts
import { template } from 'underscore';

interface User {
  name: string;
  age: number;
}

const userTemplate = template<User>('My name is <%= name %> and I am <%= age %> years old.');
const user = { name: 'Alice', age: 42 };

console.log(userTemplate(user));
260 chars
12 lines

In this example, we define an interface for the User model to ensure type safety. We then define a template string with placeholders that will be replaced with values from the user object. Finally, we create an instance of the template function with the generic type parameter set to User to ensure that the placeholders in the template string match the properties of the User model.

We can then call the template function with an object that matches the model User. This will return a string with the placeholders replaced by actual values from the user object.

Note that we can also use the _.templateSettings object to customize the template string syntax. This can be useful if the default syntax clashes with an existing templating engine.

gistlibby LogSnag