This guide adds rules that aren't usually enforced by a formatter or a linter. It is largely inspired by the ts.dev Style Guide.
For any style questions not covered in this guide, do what the code in the same file or project already does: be consistent.
Files must be encoded in UTF-8. However, you should restrict the use of UTF-8 characters to the ASCII subset.
Choose a license for your project if you have not already done so. The MIT license is a good choice, as it is the most used license among packages published on NPM. Ensure that the license is compatible with the licenses of your dependencies.
Every file should have a copyright header in the following form:
//! Copyright (c) <file-creation-year> <authors>
//! Licensed under the <license-name> (<license-link>)In the previous code, the exclamation mark signals a legal comment //! <legal comment>.
Some bundlers such as esbuild are able to preserve legal comments.
Note that you should not modify the date of the copyright on change. For the same reasons, you should not use a range of years.
Note also that we use Copyright (c) over © to avoid using a non-ASCII character.
Identifiers must use only ASCII letters A-Za-z, digits 0-9, underscore _, and dollar sign $.
| Naming style | Category |
|---|---|
PascalCase |
class / decorator / enum / enum value / function / interface / types |
camelCase |
function / module alias / function parameter / property / variable |
CONSTANT_CASE |
module-level constant / static readonly property |
a-file.ts |
filename |
-
Abbreviations in
PascalCaseUse
loadHttpinstead of, unless required by a platform name (e.g.loadHTTPXMLHttpRequest). -
No boolean variables with negative names
- const isNotEnabled = true + const isEnabled = false
-
A prefix like
is,are,has,havehelps to identify boolean variables- const enabled = false + const isEnabled = false
-
Use infinitive verbs for mutating functions, past participle and nouns for pure functions
For API familiarity, you can deviate from this rule.
-
Module alias in
camelCaseimport * as awesomeModule from "./awesome-module.js"
Some libraries use a module alias that deviates from this naming convention. The only libraries that currently fall under this exception are:
- jQuery, using
$ - Lodash, using
_ - Underscore.js, using
_
- jQuery, using
-
functions in
camelCaseIt can be practical to give a factory the same name as its return type. In this exceptional case, you can use a function name in
PascalCase.type Person = { name: string } function Person(name: string): Person { return { name } }
-
CONSTANT_CASECONSTANT_CASEindicates that a value is intended to be Immutable.// Even though per the rules of JavaScript UNIT_SUFFIXES is mutable, // the uppercase indicates that users must not modify it. const UNIT_SUFFIXES = { milliseconds: "ms", seconds: "s", }
In TypeScript, use
constassertions to prevent accidental mutations:const UNIT_SUFFIXES = { milliseconds: "ms", seconds: "s", } as const
Only symbols declared at module level or static property of a class can use
CONSTANT_CASE. Local variables declared within a function must uselowerCamelCase. -
Use single upper case character for type parameters
Commonly used type parameters:
type parameter meaning E Element K Key T Type V Value -
No underscore
_prefix and suffixExceptions:
- Unused identifiers may be prefixed by an underscore (this may be required by some linters)
- Test utility functions
- Code generators may use underscore prefix and suffix for ensuring that the identifier is not a reserved word
-
No
$prefix and suffixExcept when aligning with naming conventions of third party frameworks.
-
No redundancy
As TypeScript expresses information in types, names should not be decorated with information that is included in the type.
Some concrete examples of this rule:
- No trailing or leading underscores for private properties or methods.
- No
opt_prefix for optional parameters. - No special prefix for interfaces, unless it's idiomatic in its context.
- Suffixing
Observableswith$is a common external convention. This avoids any confusion betweenObservablesand concrete values.
-
React Components
When required by JSX, components must use
UpperCamelCase.- function goLink(props: GoLinkProps) { return <a href={...}>... } + function GoLink(props: GoLinkProps) { return <a href={...}>... }
Use /** TSDoc */ comments to document your code.
You should document all properties and methods that are not self-explanatory.
-
Omit
@paramand@returnstagsA summary is often enough. You can use these tags to add information.
/** * Average of `x` and `y`. - * - * @param x - first value - * @param y - second value - * @returns Average of `x` and `y`. */ function average(x: number, y: number): number { ... }
-
Don't declare types in
@paramor@returnsblocks, don't write@implements,@enum,@private,@overrideetc. on code that uses theimplements,enum,private,overrideetc. -
Use
@throwsIf your function may throw an exception, then you should document it with the
@throwstag./** * @throws {ParserError} */ function parse(source: string): Ast {}
-
Use
@deprecated/** * @deprecated Use {@link parse2} instead. */ function parse1(source: string): Ast {}
-
No
@override, use theoverridekeyword@overrideis not enforced by the compiler. This causes the annotations and the implementation to be out of sync.class A extends B { - /** - * @override - */ - f() { ... } + override f() { ... } } -
Use Markdown
See the Markdown style guide. You should not use headings
#, thematic breaks---, and images![]()in documentation comments. -
Use
{@link symbol}to reference an exported symbolOtherwise, use Markdown inline code.
-
Code examples
You may explicitly separate an example from the summary thanks to
@example./** * Average of `x` and `y`. * * @example * ```js * average(4, 6) * 5 * ``` */ function average(x: number, y: number): number { ... }
Code examples should not contain additional comments: It is already inside a comment. If it needs further comments, then it is not a good example.
-
Use ASCII art if it improves your documentation
Some editors such as ASCII flow can help to create diagrams. You can use standardized ASCII art like Svgbob:
```svgbob ┌──────┐ ┌──────┐ │step 1├────►│step 2│ └──────┘ └──────┘ ```
You can also generate ASCII diagrams from other textual formats.
Comments have a bad reputation. According to their detractors, they are redundant with good code. While this is true for comments that restate what the code does, it is not true for comments that explain why the code is in the way it is. To find out whether a code has enough comments, read it after a few days and request reviews.
-
Explain high-level purpose
It is often useful to add a comment that explains the purpose of a module. This can help readers to find what they search. You can also add keywords to ease searching.
-
Document implementation choice
Every time you hesitate between several choices, tell about the alternatives and why you choose a solution over another one. This is a really valuable information for your readers and future self.
-
Document fixes
A code added for fixing an issue should be documented. You can also provide the issue reference.
-
Highlight non-idiomatic code
You should comment all codes that are not conventional or derive from the style guide.
For instance, add the comment
// fallthroughwhen a switch clause falls through:switch (x) { case 1: { f() // fallthrough } case 2: g() }
-
Use tagged comments such as
TODOandFIXMEA tagged comment is a comment starting with a word in uppercase. This makes easier to search code for deficiencies or remarks. You should document which tags are usable in your codebase.
// SAFETY: this type assertion is ok because it is checked by ...You can also link an issue:
// FIXME(#<issue>): <desc> // TODO(#<issue>): <desc>
Suggested tags:
- FIXME: problematic or ugly code that needs refactoring or cleanup
- HACK: workaround to a known problem
- SAFETY: code that bypasses the type checker, but is safe
- TODO: task or feature to complete
- WARNING: code that could be misused
-
Use inline
// Comment.instead of multi-line/* Comment. */You can use
/* Comment. */to add information in an expression. For example:delay(5 /* ms */)
-
Add a space at the start of the comment
- //Comment + // Comment
-
Variables
Prefer
constoverlet. Don't usevar.Declare and initialize each variable on their own line.
- let foo, bar = 5 + let foo + const bar = 5
-
No assignment in expressions
Expressions are often considered as pure. i.e. without mutations and side effects. Thus, don't use assignment in expressions.
- const y = (x += 1)*2 + x += 1 + const y = x*2
-
No comma expressions
- const y = x++, x*2 + x++ + const y = x*2
-
Use
===and!==The double equality operators cause an error-prone type coercion. It makes code harder to understand and potentially slower to execute.
However, you may use
== nulland!= nullfor comparing againstnullandundefined. -
Use boolean expressions in conditions
The type of all conditions must conform to
boolean|null|undefined. This restriction avoids common pitfalls with implicit type coercion. The inclusion ofnullandundefinedallows the use of optional chaining:if (o?.isEnabled) { ... }
-
Avoid
defaultswitch clausesDefault switch clauses prevent TypeScript from performing an exhaustiveness check.
-
No labeled statements
Labeled statements are remnants of
goto. They allow writing spaghetti code and make harder flow analysis.
-
nullvsundefinedUse either
nullorundefinedto denote absence of a value. Nullable types can be constructed as a union typestring|nullorstring|undefined. Avoid unions with both such asstring|null|undefined.Favor API familiarity. For instance,
Map.getmay returnundefined. If you create a map-like structure, then use the same API asMap.Otherwise, choose according to your use-case and the following differences:
-
nullis serializable in JSON.JSON.parse(JSON.stringify({ prop: null })).prop === null
This can simplify the writing of unit tests:
const data = JSON.stringify({ prop: null }) assert.deepEqual(data, { prop: null })
-
An
undefinedproperty or parameter is often treated as an omitted property or parameter.The following codes are equivalent:
const { prop = 5 } = {} const { prop = 5 } = { prop: undefined } function f(param = 5) {} f() f(undefined) JSON.stringify({}) === "{}" JSON.stringify({ prop: undefined }) === "{}"
-
Optional chaining can return
undefined.const x = null const y = undefined x?.prop === undefined y?.prop === undefined
-
-
Strings and Unicode
For non-ASCII characters, use the actual Unicode character (e.g.,
∞). For non-printable characters, use a hex or Unicode escapes (e.g.,\u221e).// Perfectly clear, even without a comment. const units = "μs" // Use escapes for non-printable characters. const output = "\ufeff" + content // byte order mark
-
No primitive wrapper instantiation
Don't instantiate the wrapper classes
String,Boolean, andNumber. Wrapper classes have surprising behavior. For example,new Boolean(false)evaluates totrue.- new String("hello") + "hello"
-
Type coercion
You can use wrapper classes without
newfor explicit type conversion:Number("2e1") === 2e1 Number(1n) === 1 String(5) === "5" String(false) === "false"
Avoid string concatenation to cast to string. Use string templates or explicit conversions:
- "count: " + 5 + `count: ${5}` + "count: " + String(5)
Number,parseInt, andparseFloathave subtle differences. Know the difference betweenNumber,parseInt, andparseFloatto choose the one that fits your needs.Numbertakes any type of value and attempts to coerce it to a Number. All falsy values are converted to0. Strings containing spaces are also converted to0.parseIntandparseFloatreturnNaNwhen the parsing fails.Number(false) === 0 Number("") === 0 Number(" \t\n\v") === 0 Number("Infinity") === Number.POSITIVE_INFINITY Number("-Infinity") === Number.NEGATIVE_INFINITY Number.isNaN(Number("NaN")) Number.isNaN(parseInt(""))
NumberandparseFloatare able to parse scientific notations.parseIntandparseFloattruncate the string as soon as they encounter a non-parsable character.Number("7e2") === 700 parseFloat("7e2") === 700 parseInt("7e2") === 7 // "7e2" is truncated to "7"
NumberandparseIntare able to parse hexadecimal numbers prefixed with0x.parseIntcan also parse hexadecimal without the prefix0x.Number("0xf") === 15 parseInt("0xf") === 15 parseInt("0xf", 16) === 15 parseInt("f", 16) === 15
To avoid these pitfalls, you should validate the parsed string and the returned value:
// parse decimals if (/^[-+]\d+$/.test(s)) { const n = parseInt(s, 16) if (Number.isSafeInteger(n)) { ... } } // parse hexadecimals if (/^(0x)?[a-f\d]+$/i.test(someString)) { const n = parseInt(someString, 16) if (Number.isSafeInteger(n)) { ... } } // parse floats if (/^[-+]?\d*(\d\.|\.\d)\d*(e[-+]?\d+)?$/i.test(someString)) { const n = parseFloat(someString) if (n === Number.POSITIVE_INFINITY || n === Number.NEGATIVE_INFINITY) { ... } } // parse hexadecimals and floats if (/^(0x)?[a-f\d]+|[-+]?\d*(\d\.|\.\d)\d*(e[-+]?\d+)?$/i.test(someString)) { Number(someString) ... }
-
No
isNaNandisFinite, useNumber.isNaNandNumber.isFiniteThe global functions
isNaNandisFiniteare unsafe: they attempt a type coercion.
-
No
new Array(...)new Array()has confusing and contradictory usages. Use literal arrays instead.- const a = new Array(2) // [undefined, undefined] - const b = new Array(2, 3) // [2, 3] + const c = [2, 3]
-
No sparse arrays
Don't create sparse arrays — i.e., arrays with holes:
- const sparseArray = [1, , 2] + const sparseArray = [1, null, 2]
Note that this does not prevent you to use destructuring assignment with a hole:
const [, b] = f()
-
Use
push- arr[arr.length] = 5 + arr.push(5)
-
Use
T[]overArray<T>And
readonly T[]overReadonlyArray<T>. -
Use
readonlytuplesTuples are generally considered immutable in other languages. You should always make
readonlytuples.If you are tempted to create a type Pair, use a tuple type instead.
- type Pair<T, U> = { readonly first: T, readonly second: U } - function split(address: string): Pair<string, string> { ... } + function split(address: string): readonly [host: string, port: string] { ... }
If your tuple has three or more elements, then consider using an object literal instead.
- function split(address: string): readonly [ + function split(address: string): { protocol: string, host: string, port: string + } { ... } - ] { ... }
-
Use top-level named functions
- const f = function() { ... } - const f = () => { ... } + function f() { ... }
You may use an arrow function when you wish assigning to a typed constant.
const f: FunctionSignature = () => { ... }
-
Use arrow functions for anonymous functions
- bar(function() { ... }) + bar(() => { ... })
-
Use default parameters over optional parameters
- function ident(s: string, n?: number): string { ... } + function ident(s: string, n = 0): string { ... }
-
No mutable value for default parameters
The value of a default parameter is shared between all function calls. Thus, you must not mutate the value. Use
readonlytypes for protecting the value.+ function f(arr: readonly string[] = []): string[] { - function f(arr: string[] = []): string[] { - return arr + return arr.slice() }
-
Group default and optional parameters into an option object.
An optional parameter that's not in an options object might be acceptable if there is only one, and it seems inconceivable that we would add more optional parameters in the future.
- function connect(hostname = "localhost", port = 8080): void { ... } + function connect({ hostname = "localhost", port = 8080 } = {}): void { ... }
-
No property addition
Don't add properties to a function.
function f() {} - f.id = (x) => x -
No
.length,.namef.lengthreturns the number of parameters of a functionf. It is not reliable because default and optional parameters are not counted. Moreover, some transpilers and bundlers can change the number of parameters.f.namereturns the name of the functionf. You should not rely onf.namebecause a minifier can change the name of a function. -
Avoid overloaded functions
- function f(a: number): void - function f(a: string): void function f(a: number | string): void { ... }
The only valid use case for overloading is when the return type depends on the parameter types:
- function f(a: number): number - function f(a: string): string function f(a: number | string): number | string { ... }
Even in this case, you can create two functions to avoid overloading:
function f1(a: number): number { ... } function f2(a: string): string { ... }
-
Avoid nested named functions
Nested named function that are not closures - i.e. function that capture a variable of the super scope - should be extracted at the top-level of the module.
+ function g() { return 1 } function f() { - function g() { return 1 } return g(); }
-
No
thisthisshould only be used inside a method. It is error-prone to usethisin functions. -
Use early returns
Early returns should highlight exceptions, while the main return should highlight the happy path. This improves the code readability and avoids too many nesting.
function f() { if (a) { // exception 1 return ... } - else if (b) { + if (b) { // exception 2 return ... } - else { return ... } + return ... } -
voidvsundefinedvoidshould only be used as return type, including in generics that appear in return types.A function with
voidas return type should not havereturn <value>instructions. Areturnwithout a value is allowed as control flow instruction.In contrast, a function with
undefinedas return type must explicitly returnundefined. -
No side effects
All functions should only mutate their parameters. For instance, the following function has a side effect that modifies
env.const env = { name: "" } function modifyEnv(): void { env.name = "Lea" }
However, side effects for logging purpose are allowed:
function logSideEffect(): void { console.log("side effect") }
Note that methods can mutate their implicit parameter
this.
-
Only
throwinstances ofErroror derived classesLiteral values don't get a stack trace filled in, making debugging hard.
- throw "message" + throw new Error("message")
Consider writing your own error type:
class CustomError extends Error { override name = "CustomError" readonly data: Data constructor(data: Data) { super("message") this.data = data } }
Don't forget to set the
nameproperty to the name of your class. -
Catching and re-throwing
Use a type narrowing to handle an error. And re-throw all other kind of errors. This allows to forward unknown errors.
try { canThrow() } catch(e) { if (e instanceof CustomError) { ... } throw e }
-
Don't catch all kind of errors
Some errors are not meant to be caught. They signal a misused_API_. For instance:
AssertionErrorInternalErrorRangeErrorReferenceErrorSyntaxErrorTypeError
You should distinguish errors that signal API misuse or unrecoverable errors from recoverable and expected errors. The former group should not be caught, while the later should be caught and handled.
-
Use
enuminitializersAll
enumvalues must be initialized either with integers, or strings that match theenumname.enum Gender { - Female, - Fluid, - Male, + Female = 0, + Fluid = 1, + Male = 2, // or + Female = "Female", + Fluid = "Fluid", + Male = "Male", }In some rare cases, you can use string values that don't match the enum name:
enum Punctuation { Comma = ",", Dot = ".", }
Flags are allowed:
enum Flags { A = 1, B = 1 << 1, AB = A | B, }
-
No negative
enumvaluesNegative
enumvalue produce deoptimizations. Fallback to constants for using negative integers:type Order = -1 | 0 | 1 const LOWER = -1 const EQUAL = 0 const UPPER = 1
-
No computed access on
enumThis implies you cannot look up the name of a member from its value.
enum Gender { Female = 0, Fluid = 1, Male = 2, } - Gender["FEMALE"] + Gender.FEMALE - Gender[0] -
No
const enumconst enumforces the TypeScript Compiler to inline theenum.const enumis not supported by bundlers and is incompatible with theisolatedModulesTypeScript mode. Their use can lead to import non-existent values (becauseconst enumis erased). Moreover, some bundlers, such as esbuild, are able to inlineenumanyway.- export const enum Gender { + export enum Gender { Female = "Female" Fluid = "Fluid" Male = "Male" }
-
Assume prototype-less object literal
It is considered as a bad practice to call an inherited method of the
Objectprototype, as this method can be overridden. Moreover, an object literal can be created with a prototype set to nullObject.create(null). Thus, you should assume that an object literal doesn't inherit of the methods ofObject.const x = {} - x.hasOwnProperty("a") + Object.hasOwnProperty.call(x, "a") + // or in ES2022: + Object.hasOwn(x, "a") -
No methods, getters, and setters on object literals
If you really need methods, getters, or setters, then use a class.
- const x = { - method() { ... } - get x() { ... } - set x(val) { ... } - } + const x = new X() + class X { + method() { ... } + get x() { ... } + set x(val) { ... } + }
-
Use object destructuring assignment
An object destructuring assignment can be easier to read.
- const a = x.a - const b = x.b + const { a, b } = x
Sometimes, this allows removing a variable:
+ function f({ a, b }) { - function f(x) { - const a = x.a - const b = x.b ... }
-
.dottedvs[computed]property accessUse
[computed]for dynamic access:function(o) { for(const p in o) { const val = o[p] } }
Otherwise, use
.dotted. -
Use fixed object shapes
JavaScript engines optimize code path that use the same object shapes. i.e. object with the same property names initialized in the same order. You should ensure a consistent order in the declaration and initialization of properties:
type ServerConfig = { readonly host: string, readonly port: number, } const configs = [ { host: "localhost", port: 8080 }, - { port: 8081, host: "localhost" }, + { host: "localhost", port: 8081 }, ]You should only use optional properties at the boundary of your library where API ergonomics is important. In this case, you can rely on the
Partial<T>type:function ServerConfig({ host = "localhost", port = 8080, }: Partial<ServerConfig>): ServerConfig { return { host, port } } ServerConfig({}) ServerConfig({ port: 8081 })
If you use unions of object literal types, ensure they have the same shape:
type EmptyTree = { readonly value: null; readonly next: null } type Tree<V> = { value: V; next: Tree<V> } | EmptyTree
To create union of object literals with distinct shapes, you can use tagged unions:
type AB = { tag: "TypeA"; val: TypeA } | { tag: "TypeB"; val: TypeB } const ab: AB = ... switch (ab.tag) { case "TypeA": ... break case "TypeB": ... break }
-
No
deleteDeleting a property changes the shape of the object.
-
Avoid spreading objects
Copying an object with an object spread doesn't preserve its shape for now. For a simple copy, always copy all properties explicitly:
const x = { a: 1, b: 2 } - const y = { ...x, b: 3 } + const y = { a: x.a, b: 3 }For more complex copying, you can resort to object spread. If the copy causes too much deoptimization and hurts performance, then you can use a trick to preserve the shape of the object:
function spread(x) { return { a: 0, b: 0, ...x } } const x = { a: 1, b: 2 } const y = spread({ ...x, b: 3 }) // or const y = spread({ b: 3 })
-
Use
implements <interfaces>Although TypeScript is structurally typed, you should implement an
interfaceexplicitly. This ensures that yourclassimplements theinterfacecorrectly.A class must only explicitly implement interfaces. Don't explicitly implement a type alias. Similarly, an interface must only extend other interfaces.
-
Composition over inheritance
You should avoid inheritance and extension. Make sure you only extend classes that are designed to be extended. For example, an
abstract classis expected to be extended.When extending a class, avoid overriding methods and properties. Ensure that an instance of your class respects the invariants of the extended class. In other words, you must respect the Liskov substitution principle.
Don't extend standard types such as
Boolean,BigInt,Number,String,Array,Map,Set,Symbol,Function, etc. -
Use consistent declaration order of
classmembers- static properties (constants)
- static getter and paired static setters
- static methods (factory methods)
- properties
- constructor
- getter and paired setters
- methods
-
No
staticinitialization blocks, avoidstaticmembersUse top-level declarations instead. You can use static members for factory methods.
+ const CONSTANT = 5 class A { - static { ... } - static CONSTANT = 5 static createA(): A { ... } } }
-
No
public, avoidprotected, use#privateinstead ofprivateRestricting the visibility of properties, methods, and entire types helps to keep code decoupled.
Members are public by default. Thus, don't use
public.Avoid
protected: it is often used in an architecture that favors inheritance. You should favor composition over inheritance.If you target ES2022 or above, then use
#privateinstead ofprivate. Otherwise, useprivateto avoid substantial emit size and performance degradation.class AwesomeClass { - private property: number + #property: number }You should not mix both
#privateandprivate. You should also avoid using public and private identifiers with the same name. This is confusing. This also simplifies switching fromprivateto#privateand vice-versa.class AwesomeClass { - property: number - #property: number + public_property: number + #private_property: number }Consider converting
privatemethods to non-exported named functions:class A { - #f() {} } + function f(a: A) {} -
Use property initializers
If a class property is initialized with a constant, initialize it where it's declared. Sometimes this allows you to omit the constructor altogether.
class Foo { - private readonly userList: string[] - constructor() { this.userList = [] } + private readonly userList: string[] = [] } -
No useless
constructorIt is unnecessary to declare an empty
constructoror one that delegates into its parent class. JavaScript provides a default class constructor if one is not declared.class UnnecessaryConstructor { - constructor() {} }class UnnecessaryConstructorOverride extends Base { - constructor(value: number) { super(value) } } -
No optional properties
An instance should have a fixed object shape.
class AwesomeClass { - name?: string + name: string | null } -
No parameter properties
Parameter properties may be unfamiliar to newcomers. Moreover, they are not compatible with the new syntax for private members
#property.class Awesome { + readonly property: number; - constructor(readonly property: number) {} + constructor(property: number) { + this.property = property; + } } -
Avoid getters and setters
Use regular properties and methods instead.
You can use getters and setters if it makes the API more familiar, or if a user might expect a property.
class LinkedList { get length(): number { ... } }
Getters and setters should mimic a property. In particular:
- A getter must be a pure (no side effects) and deterministic function.
- The setter should modify the value returned by the getter with the value passed to it.
Getters and setters are notably useful for modifying the API in a backward-compatible way. For example, computing a property instead of storing it:
class List { - isEmpty: boolean // Version 1 + get isEmpty(): boolean { ... } // Version 1.1 } -
Use
thisin methods, constructors, getters, and settersAll non-static class methods should use
this. Otherwise, the method should be extracted into a top-level named function. -
Avoid
@DecoratorDon't define new decorators. Only use the decorators defined by frameworks.
- Angular:
@Component,@NgModule, etc. - Polymer:
@property, etc.
- Angular:
-
Assume immutable prototypes
The methods of a class must not be re-assigned.
-
Place imports at the top of the file after the copyright header
Imports should be sorted.
-
Use relative import paths with extensions
Use relative imports
./foorather than absolute importspath/to/foowhen referring to files within the same (logical) project. Consider limiting the number of parent steps../../../as those can make module and path structures difficult to understand.Use relative imports with extensions. The extension should end with
.jsor.ts(Deno). -
No circular imports
This prevents partial evaluation and some hard-to-catch errors. Module dependencies should form a Directed Acyclic Graph.
-
Module imports vs destructuring imports
Despite the
*, a module import is not like a "wildcard" import as seen in other languages. Instead, module imports give a name to the whole module. All symbols of the module are thus qualified with the attached module name. This makes the code more readable and provides autocompletion on all symbols in a module. They also require less import churn (all symbols are available), fewer name collisions, and allow shorter names in the imported module. Module imports are particularly useful when using many different symbols from large APIs.import * as utils from "./utils.js"
Destructuring imports give local names to every imported symbol. They allow for more concise code when using the imported symbol, which is particularly useful for very commonly used symbols.
import { test, expect } from "vitest"
Use module imports instead of destructuring imports to resolve naming conflicts:
- import { x as y } from "./utils.js" - const x = y + import * as utils from "./utils.js" + const x = utils.x
-
Use
import typeAll values that are only types (e.g.
typeandinterface) must be imported withimport typeorimport { type ... }. This allows the use of modern bundlers such as esbuild. -
No
namespacenamespaceandmoduleare legacy TypeScript constructs. Use ECMAScript Modules (ESM) instead. In contrast to TypeScriptnamespaceandmodule, ESM can be optimized by bundlers.- namespace AwesomeModule { ... } - module AwesomeModule { ... }
Note that you can use ambient modules for typing third-party modules.
-
Treat modules,
enum, andclasslike namespacesWhen importing a module, access its properties directly rather than passing the module around. This ensures that a module can be analyzed and optimized.
import * as utils from "./utils.js" - f(utils) + f({ a: utils.a, b: utils.b })
Enums and classes should also be treated like namespaces. Don't pass an
enumor aclassto a function and don't assign them to variables. -
Constant declarations
You should declare constants at the beginning of a module without any imports. Some bundlers, such as esbuild, take advantage of this to inline constants.
- import ... export const MAX_U32 = 2**32 - 1 -
No
export defaultThis ensures import uniformity and avoids historical incompatibilities between transpilers.
- export default function f() {} + export function f() {}
-
Use inline exports
- const A = ... - export { A } + export const A = ...
-
No
export * asThis type of export is confusing because this makes a namespace looks like an exported object. Also, some bundlers such as esbuild are not able to optimize this kind of exports.
You can freely use
export * from,export { X } from, andexport { X as Y } from. -
Write side-effect-free modules
All exports must be free of side effects. This is a requirement for dead code elimination.
If a constant is built from a function call, the function must be preceded by the comment
/*@__PURE__*/. This informs the bundler that the call is pure.- export const X = createX() + export const X = /*@__PURE__*/ createX()
-
Place non-exported functions and classes at the end of the file
This will allow the reader of your code to quickly scan for exported functions.
-
Type inference
Rely on type inference as implemented by the TypeScript compiler for all expressions. This simplifies code refactoring.
However, an
exportmust be explicitly typed if its type cannot be syntactically inferred. This allows every file to be type-checked separately. Anexportis syntactically inferred if it is initialized with a literal value that is recursively composed only of literal values.// Type of `f()` cannot be syntactically inferred. - export const X = { a: f() } + export const X: { readonly a: number } = { a: /* @__PURE__ */ f() } export const Y = { b: 5 } as const
All named functions, even those that are not exported, must be explicitly typed. This improves code documentation.
- function doNothings(s) { ... } + function doNothings(s: string): void { ... }
Similarly, class members must be explicitly typed.
class Person { - name + name: string - method() { ... } + method(): void { ... } } -
Nullable type aliases
Type aliases should not include
|nullor|undefinedin a union type. This typically indicates that null values are being passed around through too many layers. They also make it unclear when certain values may be missing from a type.Instead, code should only add
|nullor|undefinedwhen the alias is actually used. Code should deal with null values close to where they occur, using the techniques above.- type Coffee = Latte | Americano | null + type Coffee = Latte | Americano - function drink(): Coffee { ... } + function drink(): Coffee | null { ... }
-
Optional
?vs|undefinedtypeOptional marker
?indicates that a property or a parameter can be omitted.|undefinedindicates thatundefinedis a valid value for the property or parameter. TypeScript implicitly adds|undefinedto optional properties. You should not rely on this implicit behavior and always add|undefinedwhen it is a valid value for the property.type Named = { name?: string } - const x: Named = { name: undefined } + const x: Named = {} -
Assume nominal typing for
classTypeScript does not support nominal typing. That is, you should not assign object literals where
classinstances are expected.class Person { name: number ... } class MoralPerson { name: number ... } function f(a: Person): void { ... } - f({ name: "Eva" }) - f(new MoralPerson("AwesomeCoop")) + f(new Person("Eva")) -
interfacevs objecttypealiasYou should treat
interfaceand objecttypealias like Flow:- Object
typefor object literals interfacefor object literals andclassinstances
interface Named { name: string } type Person = { name: string } class MoralPerson implements Named {} let n: Named; let p: Person; let m: MoralPerson n = p n = m - p = n - p = m - m = n - m = pBecause of this distinction, an
interfaceshould not extend atypealias. - Object
-
Assume exact
typeNon-exact types must be explicitly marked:
// Exact type type Person = { name: string } const p1: Person = { name: "Eva", } // Inexact type type InexactPerson = { name: string [extra: string]: unknown } const p2: InexactPerson = { name: "Eva", age: 25, }
You may also use an
interfacefor inexact types. Note that this allows also using class instances (assuming nominal typing for classes).interface Named { name: string } class Person implements Named { ... } const p3: Named = { name: "Eva", age: 25, } const p4: Named = new Person("Eva", 25)
TypeScript checks exactness when you assign a literal to a typed variable and argument. You should leverage this to catch exactness errors.
type Person = { name: string age: number } const p0: Person = { name: "Eva", age: 25, isAdult: true } // ERROR const p1 = { name: "Eva", age: 25, isAdult: true } const p2: Person = p1 // NO ERROR withAdultFlag({ name: "Eva", age: 25, isAdult: true }) // ERROR withAdultFlag(p1) // NO ERROR function withAdultFlag({ name, age }: Person): Person { if (age >= 18) { return { name, isAdult: true } // ERROR } const result = { name, isAdult: false } return result // NO ERROR }
-
Use
readonlyMark properties that are never reassigned with the
readonlymodifier. These need not be deeply immutable.type Person = { - name: string + readonly name: string }Class properties may also be marked as
readonly:class AwesomeClass { - name: string + readonly name: string[] } -
Use type parameters with caution
Avoid types and functions with many type parameters. This makes your API harder to use and understand.
Think twice before adding a type parameter.
-
Avoid mapped and conditional types
Mapped types and conditional types are advanced features. They come with edge cases and make the code harder to understand.
You should avoid using them and rely on the simplest type construct that can express your code. A few repetitions are often cheaper than the long-term cost of complex types. Use the following utility types before resorting to mapped and conditional types:
Partial,Readonly, andRecord.Avoid the following utility types:
Pick,Omit,Exclude,Extract,NonNullable, andrequired. They can usually be replaced by plain types. -
No
any, useunknownanyis dangerous: it allows assignment into any other type and dereferencing any property from it. Useunknowninstead, or a type assertion as a last resort. -
No
@ts-ignore,@ts-expect-error,@ts-nocheck -
No non-null assertions
!Non-null assertions (
x!) are unsafe and unfamiliar. Use optional chaining?combined and nullish coalescing??, or in last resort type assertions.- prop!.doSomething() + prop?.doSomething()
-
Use type assertions
asAvoid type assertions. However, sometimes it is necessary to avoid complex types that use mapped and conditional types. In this case use the
assyntax, and add a comment to indicate why the assertion is valid:// z must be Awesome because ... - const y = <Awesome>z.length + const y = (z as Awesome).length
-
Type assertions and object literals
Use type annotations instead of type assertions to specify the type of object literals.
- const { + const Person = { bar: 123, bam: "abc", // no error! + } - } as Person
For constants, you can also use
as constassertions:const ANONYMOUS = { name: "Anonymous" } as const
-
Nominal type aliases
This is an advanced feature that makes the code harder to read and understand. However, it can avoid severe issue in some cases. Use with caution.
TypeScript does not support nominal type aliases natively. Flow supports nominal type aliases through sub-typing of opaque types. You can emulate nominal types in TypeScript using a brand. A brand is a fake property that changes the shape of the aliased type. For example:
/** @phantom */ declare const PERCENTAGE_BRAND: unique symbol export type Percentage = number & { readonly [PERCENTAGE_BRAND]: never } export function Percentage(n: number): Percentage { assert(n >= 0) return n as Percentage } const p = Percentage(5)
/** @phantom */ declare const PERSON_BRAND: unique symbol export type Person = { readonly name: string readonly [PERSON_BRAND]: never } export function Person(p: Omit<Person, typeof PERSON_BRAND>): Person { assert(p.name.length > 0) return p as Person } const p = Person({ name: "Hari Seldon" })
We use the JSDoc tag
@phantomto signal that the constant does not exist at runtime and thus must only be used in type contexts.We chose the type
neverfor our fake property. Nothing except anevervalue can be assigned tonever. This signals that the property should not be read.Nominal types allow checking invariants. In the previous example, we check that a person has a non-empty name. In this case, you should only use brand for immutable types to avoid invalidating data.