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.

GroupGenerics
KindSyntax
Strict modeNot 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: TThe 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.
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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏