Upgrade to Pro — share decks privately, control downloads, hide ads and more …

cookpad summer internship 2018 - JavaScript

cookpad summer internship 2018 - JavaScript

Kazuhito Hokamura

September 18, 2018
Tweet

More Decks by Kazuhito Hokamura

Other Decks in Technology

Transcript

  1. // جຊతʹ͸constΛ࢖͏ const str = 'x'; const arr = [1,

    2, 3]; // ఆٛޙʹ࠶୅ೖ͕ඞཁͳ৔߹͸letΛ࢖͏ let message; if (err) { message = 'error!';
 } else { message = 'ok!';
 } 変数宣言
  2. const num1 = 100; const num2 = 3.141592; const str1

    = 'xxx'; const str2 = "yyy"; const str3 = `foo${str}bar`; const x = null; const bool = true; const re = /foo.+$/i; リテラル
  3. const arr = [1, 2, 3]; arr[0] //=> 1 //

    for-ofͰΠςϨʔγϣϯ for (const v of arr) { console.log(v); // 1, 2, 3 } // ֤छϝιουͰΠςϨʔγϣϯ arr.forEach((v) => { console.log(v); }) //=> 1, 2, 3 arr.map((v) => { return v * 2; }); //=> [2, 4, 6] arr.filter((v) => { return v > 1; }); //=> [2, 3] 配列
  4. const obj = { foo: 'bar', fn: () => {

    console.log('hello!') } }; obj.foo; //=> 'bar' obj.fn(); //=> hello! obj.a = 'b'; // Shorthand property names const x = 1; const y = 2; const obj2 = { x, y }; // { x: x, y: y } オブジェクト
  5. // function จ function square(x) { return x * x;

    } // function ࣜ const square = function(x) { return x * x; }; // Arrow function ࣜ const square = (x) => { return x * x; }; // Ҿ਺͕1ͭͷͱ͖͸ () ΛলུՄೳɻ{ } Λলུͨ͠৔߹୯Ұͷ͕ࣜॻ͚ͯͦͷࣜͷ஋͕return͞ΕΔ const square = x => x * x; square(5); //=> 25 関数
  6. class Greeter { constructor(name) { this.name = name; } greet()

    { return `Hello ${this.name}!`; } } const g = new Greeter('hokaccha'); g.greet(); //=> 'Hello hokaccha!'; Class
  7. Modules // lib/Greeter.js export default class Greeter { constructor(name) {

    this.name = name; } greet() { return `Hello ${name}!`; } } export function hello(name) { return `Hello ${name}!`; }
  8. Modules // app.js // default import import Greeter from './lib/Greeter';

    // named import import { hello } from './lib/Greeter'; // mixed import Greeter, { hello } from './lib/Greeter';
  9. callback http.get('/a', (err, responseA) => { if (err) { return

    handleError(err); } http.get('/b', (err, responseB) => { if (err) { return handleError(err); } http.get('/c', (err, responseC) => { if (err) { return handleError(err); } // ... }); }); });
  10. Promise function get(url) { return new Promise((resolve, reject) => {

    http.get(url, (err, response) => { if (err) { reject(err); } else { resolve(response); } }); }); } get('/a').then(response => { // do something }).catch(err => { // error handling });
  11. Promise get('/a') .then(responseA => { return get('/b'); }) .then(responseB =>

    { return get('/c'); }) .then(responseC => { // do something }) .catch(err => { // error handling });
  12. async/await async function req() { const responseA = await get('/a');

    const responseB = await get('/b'); const responseC = await get('/c'); return responseC; } async function f() { try { const res = await req(); // do something } catch (err) { // error handling } }
  13. DOM

  14. <!DOCTYPE html> <html> <head> <script src="app.js" defer></script> </head> <body> <button

    id="button">Click Me!</button> <div id="message"></div> </body> </html>
  15. // HTMLʹॻ͔Ε͍ͯΔ button ཁૉΛऔಘ const button = document.getElementById('button'); // click͞Εͨͱ͖ͷϋϯυϥʔΛొ࿥

    button.addEventListener('click', async () => { // HTTP RequestͰAPIΛݺͼग़͢ const response = await fetch('/message'); const body = await response.json(); // #messageͷ಺༰Λॻ͖׵͑Δ document.getElementById('message').innerHTML = body.message; });
  16. // HTMLʹॻ͔Ε͍ͯΔ button ཁૉΛऔಘ const button = document.getElementById('button'); // click͞Εͨͱ͖ͷϋϯυϥʔΛొ࿥

    button.addEventListener('click', async () => { // HTTP RequestͰAPIΛݺͼग़͢ const response = await fetch('/message'); const body = await response.json(); // #messageͷ಺༰Λॻ͖׵͑Δ document.getElementById('message').innerHTML = body.message; }); %0."1*
  17. JavaScript function greeter(person) { return "Hello, " + person; }

    const user = "hokaccha"; const message = greeter(user);
  18. TypeScript function greeter(person: string): string { return "Hello, " +

    person; } const user = "hokaccha"; const message = greeter(user);
  19. TypeScript function greeter(person: string): string { return "Hello, " +

    person; } const user = [1, 2, 3]; const message = greeter(user); //=> error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.
  20. Basic Types let str: string; let num: number; let bool:

    boolean; let arr: string[]; let fn: (a: string, b: string) => boolean; type StrOrArr = string | string[]; type StrOrNull = string | null;
  21. Generics class Queue<T> { private data: T[] = []; enqueue(item:

    T) { return this.data.push(item); } dequeue(): T { return this.data.shift(); } } const queue = new Queue<number>(); queue.enqueue(10); queue.enqueue('x'); // Error!
  22. Generics interface User { name: string; } async function getUser():

    Promise<User> { const response = await fetch('/user'); const body = await response.json(); return body; } async function f() { const user: User = await getUser(); }
  23. // Ҿ਺ͷܕ͕anyʹͳΔͷͰͲΜͳܕͰ΋௨Δ function greeter(person) { return "Hello, " + person;

    } const user = [1, 2, 3]; const message = greeter(user); //=> ok Gradual Typing
  24. interface Person { firstName: string; lastName: string; } class User

    { firstName: string; lastName: string; } const user1: Person = new User(); // ok const user2: Person = { firstName: "Kazuhito", lastName: "Hokamura" }; // ok Structural Subtyping
  25. class User { name: string; } class Product { name:

    string; } const user: User = new Product(); // ok const product: Product = new User(); // ok Structural Subtyping
  26. class App extends React.Component { constructor(props) { super(props); this.state =

    { name: '' }; } handleInput(event) { this.setState({ name: event.target.value }); } render() { return <div> <input type="text" onInput={event => this.handleInput(event)} /> <div>Hello, {this.state.name}</div> </div>; } } ReactDOM.render(<App />, document.getElementById('app'));
  27. class Button extends React.Component { render() { return <button onClick={()

    => this.props.onClick()}> <i className={`icon-${this.props.icon}`} /> {this.props.label} </button> } } <Button label="Click Me" icon="caret" onClick={() => alert('Hi!')} /> JSX
  28. Lists and Keys class App extends React.Component { render() {

    // users: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] const items = this.props.users.map(user => { return <li key={user.id}>{user.name}</li>; }); return <div>{items}</div>; } }
  29. interface State { name: string; } interface Props { defaultName:

    string; } class App extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = { name: props.defaultName }; } handleClick() { this.setState({ a: 'b' }); // Error } } <App foo="bar" />; // Error With TypeScript
  30. class Greeter extends React.Component<{}, {}> { render() { return <div

    className="greeter">Hello, {this.props.name}</div>; } } // ୯ͳΔؔ਺ͱͯ͠΋ఆٛͰ͖Δ function Greeter(props) { return <div className="greeter">Hello, {this.props.name}</div>; } Stateless Component
  31. class App extends React.Component { constructor(props) { super(props); this.state =

    { name: '' }; } handleInput(event) { this.setState({ name: event.target.value }); } render() { return <div> <input type="text" onInput={event => this.handleInput(event)} /> <Greeter name={this.state.name} /> </div>; } } Container Component
  32. Fetch data class App extends React.Component { constructor(props) { super(props);

    this.state = { name: '' }; } async componentDidMount() { const response = await fetch('/user'); const body = await response.json(); this.setState({ name: body.name }); } render() { // ... } }
  33. 環境構築 $ npm install -g create-react-app $ create-react-app booklist-front \

    --scripts-version=@hokaccha/create-react-app-ts-dev $ cd booklist-front $ yarn start