`.d.ts` files and typescript interfaces

2019-03-08

 | 

~2 min read

 | 

220 words

The .d file is a declaration file. In this case, it’s a declaration file for Typescript files.

What does that actually mean though? The declaration file acts as an interface with other Javascript files so that they do not need to be re-written in typescript while still getting the benefits of having some parts of the code base be typed.

In my case, I came across a updateUserPreferences method that relied on accessing the entity UserPreferences.

import { entities } from "entitySourceLibrary";
import UserPreferences = entities.userPreferences;
...
export const updateUserPreferences = async (userId: string, preferences: UserPreferences, referer: string): Promise<UserPreferences | undefined> => {
 ...
 const displayFullName = preferences.displayFullName;
 const anUnknownField = preferences.anUnknownField;
}

Unknown Property Error

When I tried to access a field that didn’t exist in the entity, however, Typescript alerted me. Even more to the point, this is a fatal error and the code will not compile correctly until this is addressed.

Fortunately, defining the entity is pretty straightforward:

export interface UserPreferences {
    userId: string;
    ...
    displayFullName?: string;
    ...
}

If I wanted to be able to use the anUnknownField in my program, I would add it to the entity file.

export interface UserPreferences {
    userId: string;
    ...
    displayFullName?: string;
   anUnknownField?: string;
    ...
}

StackOverflow on the topic: About “*.d.ts” in TypeScript



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!