Typescript interfaces: Difference between revisions
From wikinotes
(Created page with "In typescript, interfaces are implicit -- any object that satisfies the requested interface is allowed.<br> Interfaces can be extended (grown) into new interfaces that include others. = Interface = <blockquote> <syntaxhighlight lang="typescript"> interface Person { firstName: string; lastName: string; } interface Employee extends Person { id: number; } </syntaxhighlight> </blockquote><!-- Interface --> = Type Alias = <blockquote> You can also define a type...") |
m (Will moved page Typescript interface to Typescript interfaces without leaving a redirect) |
||
(2 intermediate revisions by the same user not shown) | |||
Line 6: | Line 6: | ||
<syntaxhighlight lang="typescript"> | <syntaxhighlight lang="typescript"> | ||
interface Person { | interface Person { | ||
name: string; | |||
} | } | ||
Line 13: | Line 12: | ||
id: number; | id: number; | ||
} | } | ||
function getId(employee: Employee): number { | |||
return employee.id; | |||
} | |||
getId({ id: 1, name: "vaderd" }); // valid (has both 'id', 'name') | |||
getId({ id: 2, name: "palpatine", isRoot: true }); // valid (extra param ignored, interface matched) | |||
getId({ name: "lukes" }) // invalid (missing id) | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Interface --> | </blockquote><!-- Interface --> |
Latest revision as of 00:30, 17 December 2022
In typescript, interfaces are implicit -- any object that satisfies the requested interface is allowed.
Interfaces can be extended (grown) into new interfaces that include others.
Interface
interface Person { name: string; } interface Employee extends Person { id: number; } function getId(employee: Employee): number { return employee.id; } getId({ id: 1, name: "vaderd" }); // valid (has both 'id', 'name') getId({ id: 2, name: "palpatine", isRoot: true }); // valid (extra param ignored, interface matched) getId({ name: "lukes" }) // invalid (missing id)
Type Alias
You can also define a type-alias, but you cannot
extend
it in a new interface.type Point { x: number; y: number; }