Last active
September 1, 2019 13:43
-
-
Save mathieu-anderson/dc2516ef64c3b2cefa8b7b23f2c1c1c4 to your computer and use it in GitHub Desktop.
Using generics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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