Skip to content

Instantly share code, notes, and snippets.

@mathieu-anderson
Last active September 1, 2019 13:43
Show Gist options
  • Save mathieu-anderson/dc2516ef64c3b2cefa8b7b23f2c1c1c4 to your computer and use it in GitHub Desktop.
Save mathieu-anderson/dc2516ef64c3b2cefa8b7b23f2c1c1c4 to your computer and use it in GitHub Desktop.
Using generics
import * as React from "react";
import { render } from "react-dom";
// Defining types
type InputValue = string | number;
type Label = string;
// Defining an interface
interface InputProps {
value: InputValue;
label: Label;
}
// Using generics
interface GenericInput<T> {
value: T;
label: Label;
}
function GenericTSInput<T extends InputValue>(props: GenericInput<T>) {
const { value, label } = props;
return (
<div className="container">
<div className="label">{label}</div>
<div className="typeof">
Type: <b>{typeof value}</b>
</div>
<input value={value} />
</div>
);
}
function App() {
return (
<div className="App">
<GenericTSInput<number> value={1} label="TS generic type (number)" />
<GenericTSInput<string> value="Value" label="TS generic type (string)" />
</div>
);
}
const rootElement = document.getElementById("root");
render(<App />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment