In TypeScript, we can define a generic type using <>
syntax. For example, a simple Identity
function that returns the same value it receives would look like this:
index.ts52 chars4 lines
To express this in plain JavaScript, we can use template literals, which allow us to define a string with placeholders that can be replaced at runtime:
index.tsx43 chars4 lines
The T
type parameter is no longer necessary, as JavaScript is a dynamically-typed language. If we want to restrict the type of the argument to a specific interface, we can do this:
index.ts132 chars8 lines
In JavaScript, we can achieve the same effect using plain object arguments and template literals:
index.tsx61 chars4 lines
Note that we don't have a way to enforce the HasName
interface in JavaScript, but we can still use it as a documentation tool.
gistlibby LogSnag