30
loading...
This website collects cookies to deliver better user experience
namespace
allows you to access its exported values or types using dot-notation. While it's not recommended to use namespace
in today's code (hello, not standard EcmaScript), it's still recommended and useful for describing and organizing types.declare
keyword in front of the namespace
keyword to make it an ambient declaration. Then use the same name of the entity (interface / type / class / ...) – that you want to merge with – as the namespace name. Look at the following examples:User
and UserDetails
interfaces, we can just define a single User
interface and use ambient namespace declaration to export sub types:// example.ts
interface User {
FirstName: string
LastName: string
Details: User.Details
}
declare namespace User {
interface Details {
Address: string
}
}
const details: User.Details = {
Address: "Somewhere over the rainbow"
}
const user: User = {
FirstName: "Bob",
LastName: "Alice",
Details: details,
}
declare
keyword, there is no need to export
the Details
interface (auto-exported).// example.ts
interface User {
FirstName: User.FirstName
LastName: User.LastName
}
declare namespace User {
type FirstName = string & { __brand: "User:FirstName" }
type LastName = string & { __brand: "User:LastName" }
}
const firstName = <User.FirstName>"Bob"
const lastName = <User.LastName>"Alice"
const user: User = {
FirstName: firstName,
LastName: lastName,
}
In .tsx files: use "Bob" as User.FirstName
and "Alice" as User.LastName
// example.ts
interface Foo<
T = Foo.T,
V = Foo.V,
S = Foo.S<T>,
> {
/** property types here */
}
declare namespace Foo {
type T = string
type V = string
type S<T> = { t: T, something: string }
}
const foo: Foo<
Foo.T,
Foo.V,
Foo.S<Foo.T>
> = {}
Callback
– we could use ambient namespaces:// example.ts
const foo = <const>{
trigger(cb: foo.Callback): void { }
}
declare namespace foo {
interface Callback {
(value: string): void
}
}
const myCallback: foo.Callback = (value: string): void => {
return void console.log(value)
}
foo.trigger(myCallback)
This also applies to classes, enums, and functions.