TypeScript
TS08

TS07 Exercises

  1. Write a declaration file for a module simpleModule that exports a function greet which returns a string.
declare module "simpleModule" {
    export function greet(): string;
}
  1. Declare a global variable appName of type string.
declare const appName: string;
  1. Declare a global function logMessage that takes a message string as an argument and returns void.
declare function logMessage(message: string): void;
  1. Declare an object config with properties port (number) and environment (string).
declare namespace config {
    let port: number;
    let environment: string;
}
  1. Declare a class Logger with a method log and a property level.
declare class Logger {
    level: string;
    log(message: string): void;
}
  1. Create a declaration file that defines types UserID and User and use them in function declarations.
declare type UserID = number | string;
declare interface User {
    id: UserID;
    name: string;
}
 
declare function getUser(id: UserID): User;
declare function setUser(user: User): void;
  1. Write a brief explanation of how to publish .d.ts files either by bundling them with a package or publishing to the @types organization.

To publish .d.ts files, there are two main approaches:

  1. Bundling with the Package: Include the .d.ts files in the same package as the JavaScript code. This is typically done by specifying the "types" or "typings" field in the package.json file, pointing to the main .d.ts file.

  2. Publishing to @types: For libraries that do not provide their own types, type declarations can be contributed to the DefinitelyTyped repository. Once merged, they are available under the @types scope on npm. This allows users to install the types separately using their respective package managers (e.g., pnpm install @types/library-name).