interface<T> Generic Interfaces
Last updated: 2026-10-22
interface<T> Generic Interfaces
A generic interface takes type parameters (interface ApiResult<T>), decoupling the container's shape from its contents: ApiResult<UserBrief> and ApiResult<number[]> share one structure with different payloads. Interfaces, API responses and storage types all get reused through it.
| Group | Generics |
|---|---|
| Kind | Syntax |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
interface ApiResult<T> {
code: number;
data: T;
}
// Multiple type parameters and defaults are supported
interface Paginated<T, Page = number> {
page: Page;
items: T[];
}
⚙️ Parameters
| <T> | Type parameter: filled with a concrete type at use (ApiResult<UserBrief>), or inferred from context |
|---|---|
| data: T | The payload field links to T: res1.data is UserBrief automatically, checked on read and write |
Returns:Generic interfaces are a type-level concept with no runtime code; the instantiated type determines field read/write types.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
Ada admin 20
(Runtime output after transpilation; putting a number into res1.data or reading res2.data.name is a compile error — T is fixed)
💡 Notes
ℹ️ Info Type parameters must be supplied when using a generic interface (unless it has a default): a bare ApiResult is un-instantiated and cannot serve as a variable type.
💡 Tip Compose for nesting: ApiResult<Paginated<Order>> layers cleanly, clearer than hand-flattening code/data/page/items into one type.
⚠️ Note Don't generalize for its own sake: if an interface is used once with a fixed type, a concrete type is clearer. Generics pay off when one shape serves many payloads.
🏷️ Related Generics
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q Generic interface or generic type alias?
A Nearly equivalent in power. interface for declaration merging, extends hierarchies, class implements; type for unions, mapped and conditional composition.
Q Generic method vs generic interface?
A In interface Box<T> { open(): T }, T is shared across the whole interface (one Box<string> has one T everywhere); in interface Maker { make<T>(): T }, T is fixed per call. Container vs action.
Q Can a generic interface constrain its type parameter?
A Yes, same syntax as functions: interface KeyedStore<T extends { id: string }> { get(id: string): T | undefined } — non-conforming types error at the use site.