How to declare a type globally in a project (typescript)
You can create a definition file, ending with the .d.ts
extension, and place it in your project where you'd like:
user.d.ts
interface IUser {
name: string,
mail: string
}
This is also a good way to fill missing global types. I have a lib/global
folder per project to place these files.
This only works with type definitions, not actual code, as (1) that actual code would have to be imported some way, (2) .d.ts
is ambient. Also, for types defined this way to be globally visible, the corresponding declaration file should not contain top-level exports (otherwise the declaration file will be regarded as a module, requiring an import to access its types).
You can also declare modules:
declare module "my-module" {
export declare class Something {
public something: number;
}
}
And then TypeScript will allow the following:
import { Something } from "my-module";
Create global.d.ts in your project root.
Here is an example of how to declare global types constants and interfaces that will be understood globally
//example import for externally loaded library
//this will not form part of the bundle but will allow typescript to understand external libraries throughout the project
import _ from 'lodash';
declare global {
//Example global constant for libraries served via webpack externals. example webpack config:: externals: { _: 'lodash' }
//This assumes lodash was already load in DOM for example in <head> via CDN link before main.js is loaded.
const _: typeof _;
//example of custom types
type JSONPrimitive = string | number | boolean | null;
type JSONValue = JSONPrimitive | JSONObject | JSONArray;
type JSONObject = { [member: string]: JSONValue };
//example of custom interface
interface JSONArray extends Array<JSONValue> {}
}