Share
Embed
Transcript
140 slides
-
杯♏סنٞ٤عؙ٤غמ חַי React ٝؕؓؗع磝׳׆כעה؆յؓوٛ آ٭ب٘٤ֿ辐炐ױךס孱縒ֻ יײכ䑒釐כ湳閁㛡ׂםזי׀ ױն Frontend Developer Roadmap:
Learn to become a modern frontend developer React JavaScript #hatenaintern -
: React 1. TypeScript JavaScript 2. Web 3. Web html
4. (accessibility, a y) TypeScript - TypeScript Deep Dive #hatenaintern -
: React ˝ Web ˝ ˝ (accessibility, a y) ⪮⛮氳מעלֹסֹמ㵚瓀יַׂס
־յꝧ氦ס孱כ⪦מ釤יַ׀ױն #hatenaintern -
: React React JavaScript html > ls index.html main.js <!--
index.html --> <html> <head> <script type="module" src="main.js"></script> </head> </html> #hatenaintern -
: React React/TypeScript <!-- index.html --> <html> <head> <script type="module"
src="main.tsx"></script> </head> <body> <div id="root"></div> </body> </html> // main.tsx const App = () => { const user: User | null = useUser() return ( <div> Α͏ͦ͜ɺ{user?.name ?? 'ήετ'}͞Μɻ </div> ) } const container = document.getElementById('root') const root = createRoot(container!) root.render(<App />) #hatenaintern -
: React TypeScript JavaScript const user = useUser() TypeScript const
user: User | null = useUser() jsx jsx const label = () => (<div>...</div>) HTML ES ?. ?? => JSX TypeScript JavaScript Null (??) - JavaScript | MDN (?.) - JavaScript | MDN JSX React #hatenaintern -
عٚ٤تقٜؕ 僃二ס乃嫎ך傴ַגؤ٭غ㛡ׂסַ梪㗞ַهٚؗاםלך Ⳃֹׂמַ鋗嫎㚺䬵׆כ Null (??) const hello = (name) =>
`hello, ${name ?? "ήετ"}!` hello("hatena") // > hello, hatena! hello() // > hello, ήετ! #hatenaintern -
عٚ٤تقٜؕ ES (ES ) Null (??) ES var hello =
function hello(name) { return "hello, " + (name !== null && name !== void 0 ? name : "ήετ") + "!" } hello("hatena") // > hello, hatena! hello() // > hello, ήετ! #hatenaintern -
ص٭ٜزؘؕ٤ 3 (Rome , Deno ) عٚ٤تقؕٚ Babel (JavaScript) SWC
(Rust) esbuild (Golang) ف٤غٚ Webpack Rollup Parcel (SWC) Snowpack, Vite (esbuild) https://deno.land/ https://rome.tools #hatenaintern -
Web Chrome, IE, Safari, Firefox Web API JavaScript(ECMAScript) HTML DOM
API CSS API poly ll JavaScript transpile 2021 | gihyo.jp Web standards ( ) - MDN Web Docs : | MDN #hatenaintern -
Web هٚؗاׇכסئَ٭ع敯媲ע♓┖סئؕعך澬鏀׆כֿך׀ױն MDN https://developer.mozilla.org/ja/docs/Web MDN Can I use https://caniuse.com mozilla
Google Open Web Docs https://opencollective.com/open-web-docs/updates/ introducing-open-web-docs #hatenaintern -
(accessibility, a y) ( HTML) alt (Tab ) HTML -
| MDN Semantics ( ) - MDN Web Docs : | MDN #hatenaintern -
قنؚ٭ُ٤ت㵚瓀 ⮵榫⯆ֿ־־זיַ鷐ַ٬┘㱦㲊םؕ٤ذ٭ؾشع✳זיַٗ٭ا٭ֿ ╚מ㵚霄כםն js css 1 => 僃⮣סً٭ةמ䑒釐םסדׄرؗ٤ٞ٭غי碛企ׂ辐炐׀ Cumulative Layout
Shift (CLS) https://web.dev/i n/ja/cls/ #hatenaintern -
قنؚ٭ُ٤ت㵚瓀 ⮵榫⯆ֿ־־זיַ鷐ַ٬┘㱦㲊םؕ٤ذ٭ؾشع✳זיַٗ٭ا٭ֿ╚מ㵚霄כם ն (CDN, Edge) CDN 1 (Code Splitting) (preload,
defer, lazy) #hatenaintern -
: React 1. TypeScript JavaScript 2. Transpile, Polyfill Bundle, Code
Splitting 3. Web html 4. #hatenaintern -
JavaScript ( min) ES (ES ) JavaScript JavaScript JavaScript ·
JavaScript Primer #jsprimer #hatenaintern -
1/2 // มͱએݴ var a = "a" // มʢάϩʔόϧʣ let
b = "b" // มʢϩʔΧϧʣ const c = "c" // ఆ /* ҙ * var Λ༻͍ͨมએݴɺ window ΦϒδΣΫτΛ্ॻ͖ͯ͠͠·͏ */ var console = null console.log("xxx") // Error: window.console is null const id = "1234" // string const name = null // null const age = 2022 // number const isAdmin = false // boolean // object const user = { id, username: name age, isAdmin, memo, } user.age // 2022 // ະఆٛϓϩύςΟͩͱ undefined ͕ฦΔ user.abc #hatenaintern -
2/2 // ؔ function getUser(id) { return db.users.find(id) } const
getBlog = (id) => { return db.blogs.find(id) } // ྻ const array1 = [1, 2] const array2 = new Array(1, 2) // ྻॲཧ for (elm in array1) { console.log(elm) } array2.forEach((elm) => { console.log(elm) }) array1.map((elm) => elm * 2) // [2, 4] array2.at(0) // 1 #hatenaintern -
Arrow Function ˝ functionreturn✳מ꞊丗榟䡗ך׀ ˝ 㓹儖氳מע׆ס亠嫎ך꞊丗榟䡗יֽׄףـُםַ const hello = (name)
=> `Hello, ${name}` hello("world") // hello, world 1 () Tips: () const getProps = () => ({ a: "foo", b: "bar" }) this Arrow Function #hatenaintern -
Arrow Function ˝ 䌕丗ֿ邾丗ֵ㕙⺬ע()ך㍱ֹ ˝ ꞊丗⫂ס鋗鳭ֿ邾丗车מ峚כ׀ע{}כreturn榫ַ const hello = (name,
lang) => { if (lang === "ja") return `͜Μʹͪɺ${name}` if (lang === "es") return `Hola, ${name}` return `Hello, ${name}` } #hatenaintern -
Promiseמחַי Pending( ) (resolve) Fulfilled (reject) Rejected Fulfilled Rejected (
) Settled then catch const sleep = (ms) => new Promise((resolve) => { setTimeout(() => resolve(ms), ms) }) sleep(1000) .then((ms /* resolveͨ͠Λड͚औΕΔ */) => console.log(`sleep: ${ms}ms`)) .catch((e) => { console.error(e) }) #hatenaintern -
fetch✳זג❆ fetch HTTP API Promise Promise console / /* ϢʔβʔใΛऔಘ͢ΔAPIͷྫɻҎԼͷΑ͏ͳJSON͕ฦͬͯ͘Δͱ͍͏ఆɻ
{ user: {id: 1, name: 'hatena'} } */ const promise = fetch("https://api.example.com/user/1") .then((res) => res.json()) .then((json) => json.user) .then((user) => { console.log(`${user.name}ͷid${user.id}`) }) .catch(console.error) console.log(promise) // Promise {<pending>} ɾɾɾ ᶃ #hatenaintern -
Promise Promiseס鿥⮛⛼䡗յא䣽ֹ׆כך䴧⛍氳ם┾⮛⭚杼车ֹ׆כֿ⭳全ն const promises = urls.map((url) => fetch(url)) // ෳͷAPIͳͲΛฒྻʹୟ͘
Promise.all() Resolve( ) 1 Reject Promise.allSettled() Resolve Reject Promise Promise: {status: 'fulfilled', value: resolveͨ͠}, Promise: {status: 'rejected', reason: reject͞ΕͨΤϥʔ} #hatenaintern -
Promise const promises = [ getFromCache(), // cache͕ۭͷͱ͖ࣦഊ͢Δ getFromApi(), ]
Promise.race() 1 Promise Resolve Reject Promise.any() Resolve Promise Reject #hatenaintern -
async/await async function await Promise try {} catch (e) {}
async function throw const getUser = async (id) => { try { const res = await fetch(`https://api.example.com/user/${id}`) const json = await res.json() const user = json.user console.log(`${user.name}ͷid${user.id}`) return user } catch (e) { console.error(e) throw new Error("error reason: *********") } } ECMAScript Top-level await async function await #hatenaintern -
async/await async function Promise Promise then Promise await getUser(1) .then(console.log)
// {id: 1, name: 'hatena'} .catch(console.error) ˝ 扛⺲꞊丗כי㲔车׆כה؆⭳全 ;(async () => { const user = await getUser(1) console.log(user.name) // 'hatena' })() #hatenaintern -
class ES class class Rect { constructor(width, height) { this.width
= width this.height = height } // gettersetterΛఆٛͰ͖Δ get area() { return this.getArea() } getArea() { return this.width * this.height } } const rect = new Rect(5, 10) console.log(rect.area) // 50 function class https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritanceandtheprototypechain #hatenaintern -
ECMAScript Modules ٓةٖ٭ٜ 1 == 1 import/export CommonJS Node.js ECMAScript
Node.js Babel 1 webpack JavaScript ECMAScript JavaScript ECMAScript JavaScript ( ) module.exports require https://nodejs.org/docs/latest/api/modules.html #hatenaintern -
default export // module.js export default function doSomething() {} ˝
export defaultךؙؠتَ٭عכյimport侇מע♳䙫ס⺲ ⯥錃㲊ך׀ import awesome from "./module" #hatenaintern -
(named export) ˝ constך㚺丗㲚銧כ׀מexport♀ⱶ׆כך⺲⯥♀׀ؙؠتَ٭عֿ⭳ 全 // namedModule.js export const logType
= { error: 'error', log: 'log' }; export const log = (message, type) => { if (type === 'error') return console.error(message); return console.log(message); } export const hello => log('hello'); #hatenaintern -
ؕ٤َ٭عס亠嫎מחַי export import { log, hello } from "./namedModule" ˝
asךٛؾ٭ّ⭳全 import { logType as LOGTYPE } from "./namedModule" * as export import * as Logger from "./namedModule" Logger.hello() // 'hello' (webpack TreeShaking ) * as #hatenaintern -
for...of (iterable) NodeList Map Set const iterable = [10, 20,
30] for (const value of iterable) { console.log(value) } #hatenaintern -
Nullish coalescing operator ?? JavaScript || const rect = (width:
number, height?: number) => ({ width: width, height: height || 100, // ߴ͞Λলུͨ͠ͱ͖σϑΥϧτΛ༩͑Δ }) rect(50, 0) // {width: 50, height: 100} 0 ''( ) Falsy height 0 ?? null undefined ?? ?? !!0 !!'' boolean false JavaScript false null undefined NaN Falsy boolean true Truthy https://developer.mozilla.org/en-US/docs/Glossary/Falsy JavaScript || Truthy Falsy && Falsy Truthy #hatenaintern -
Optional chaining ?. ˝ ؛هةؘؠعֿnullundefinedם⺎耆䓪ֵֿכ׀յאס؛هةؘؠعסوٞقطؔ⽛שג״מifמ⮆㹎&&מ湾 礘鍐❫傴ׂ䑒釐ֵֿזגն const val = nullOrObject
&& nullOrObject.method() const result = val && val.methodOfReturnValue() ˝ .?榫ַכյ⽛צ⭳⩕ֿnullױגעundefinedסכ׀עא♓סوٞقطؔؓؠجتםַնױגյאס㕙⺬ע undefinedכי鍐❫ն const result = nullOrObject?.method()?.methodOfReturnValue() nullOrObjectnullOrObject.method()ס鲭⡁ֿ⪦מnullךundefinedךםַכ׀מյ nullOrObject.method().methodOfReturnValue()ס磵冽䐂ն && Falsy null undefined && || Falsy Optional chaining #hatenaintern -
Spread Syntax ˝ ...✳ֹכ鿥⮛؛هةؘؠع㷣ꝧ⭳全 const sum = (a, b, c,
d) => a + b + c + d const nums = [1, 2] const copied = [...nums] // தΛෳͨ͠ྻΛ࡞ΕΔ const moreNums = [...copied, 5] // [1, 2, 5] sum(...nums, 10) // 18 const obj = { a: 10, b: "foo" } const obj2 = { b: "bar", c: true } // 2ͭҎ্ͷobjectΛmerge͢ΔɻΩʔ͕ॏෳ͍ͯ͠Δ߹ޙʹॻ͍ͨํͰ্ॻ͖͞ΕΔ const merged = { ...obj, ...obj2 } // {a: 10, b: 'bar', c: true} const getUserConfig = (received) => ({ force: false, allowJs: false, ...received, // σϑΥϧτΛ͞Ε͕ͨ͋Ε্ॻ͖͢Δ }) #hatenaintern -
Rest Parameters ... Spread Syntax 1 // const sum =
(num1, num2, ...nums) => num1 + num2 + nums.reduce((a, b) => a + b, 0) const numbers = [1, 2, 3] sum(3, ...numbers, 6) // 15 #hatenaintern -
TypeScript is JavaScript JavaScript JavaScript node React JavaScript JavaScript API
Uncaught TypeError: Cannot read property 'foo' of undefined JavaScript Alternative JavaScript TypeScript #hatenaintern -
tsc: TypeScript compiler TypeScript TypeScript https://github.com/microsoft/TypeScript TypeScript JavaScript ( )
--noEmit TypeScript JavaScript JavaScript ( ) JavaScript Babel, esbuild babel @babel/preset-typescript babel enum enum typeof JavaScript ( ) #hatenaintern -
㚺丗㲚銧侇ס㑔ؓؿط٭ب٘٤ // JavaScriptͷ߹ const a = 'hello'; // TypeScriptͷ߹ม໊ͱ=ͷؒʹ:Λஔ͍ͯܕΞϊςʔγϣϯΛॻ͘ const
a: ʲ͜͜ʹܕΞϊςʔγϣϯʳ = 'hello'; // ྫ͑ const a: string = 'hello'; ׆ַׂדזג䫟鑜יׂסךյ㲔꤀מע傴־םַ׆כ 㛡ַ #hatenaintern -
: string, number, boolean, null, undefined 'hello', 12, true, false
( ) const a: number = 10 const b: boolean = false const c: string = 11 // Type Error const d: "hello" = "hello" const n: null = null ˝ 鿥⮛ const arr: string[] = ["hello", "world"] const arr2: Array<number> = [1, 2, 3, 5, 8] const arr3: [string, number] = ["year", 2021] // λϓϧ(Tuple)ܕͱ #hatenaintern -
JavaScript ? const person: { name: string age: number address?:
string } = { name: "john", age: 21, } string | undefined JavaScript (Object.keys() ) TypeScript . exactOptionalPropertyTypes tsc #hatenaintern -
type type✳ֹכ㑔辐杯מؙؕٛؓت♀ׄ type Person = { name: string age: number
} type Team = Person[] #hatenaintern -
Union Type ( ) 邾丗ס㑔סַ־嵹ג type Primitive = string |
number | boolean | undefined | null type Color = "red" | "green" | "blue" | "yellow" | "purple" #hatenaintern -
typeof ( " " JavaScript ) 'string', 'number', 'boolean', 'object',
'function', 'undefined' console.log(typeof "hello world") // 'string' const n = 10 console.log(typeof n) // 'number' const p: Person = { name: "jonh", age: 20 } console.log(typeof p) // 'object' console.log(typeof undefined) // 'undefined' console.log(typeof null) // 'object' console.log(typeof ["a"]) // 'object' #hatenaintern -
typeof ˝ 攐מnumberstringךֵ׆כמ⯆גַכ׀מ값⭳ // paddingʹۭനͷ·ͨλϒจࣈͳͲ͕ͬͯ͘Δ͜ͱΛఆͨؔ͠ const padLeft = (val: string,
padding: string | number) => { if (typeof padding === "number") { return " ".repeat(padding) + val } // padding͕numberͰͳ͍ͷͰɺstringͰ͋Δͱਪ͞ΕΔ return padding + val } #hatenaintern -
in API type Fish = { name: string swim: ()
=> void } type Bird = { name: string fly: () => void } const move = (x: Fish | Bird) => { if ("swim" in x) { // swim͕༗ΔͷFishܕͷΈ return x.swim() } // ͳͷͰɺ͜͜ʹ౸ୡ͢ΔͱBirdܕͰ͋Δͱ͔Δ return x.fly() } #hatenaintern -
Object.hasOwn() 2022/08/18 TypeScript ES Object.hasOwn() const move = (x: Fish
| Bird) => { if (Object.hasOwn(x, "swim")) { // swim͕༗ΔͷFishܕͷΈ͚ͩͲɺ Fish͔ Bird͔ͷͲͪΒ͔ΛఆͰ͖ͳ͍ return x.swim() // error: Property 'swim' does not exist on type 'Fish | Bird'. } ... } Support for Object.hasOwn (lib.d.ts and narrowing) · Issue # · microsoft/TypeScript #hatenaintern -
Tagged Union Types ˝ typekindסֹםوٞقطؔמٛطٜٚ㑔錃㲊יַֽיյאס╈骰===switch✳זי奂鬳׆כךյ㑔ס礓鱮ײ车ֹ ˝ ⠕☔氳ם䚉釶דכյinךס礓鱮ײ׆הסقذ٭٤ס亠ֿׂ⮵榫妳ֿױ ˝ ٛطٜٚ㑔ס奂鬳ס亠ֿ傴ׂסֿ癨ⶡךյ־ח׆הסֹֿ㱦⪒ךն type
Fish = { kind: "fish" name: string swim: () => void } type Bird = { kind: "bird" name: string fly: () => void } const move = (x: Fish | Bird) => { if (x.kind === "fish") { return x.swim() } return x.fly() } #hatenaintern -
as JavaScript // ܕFooΛՃ͢Δ type Foo = { bar: number
piyo: string } const something = (x: Foo) => { // ܕͱͯ͠߹͍ͬͯΔ͕ɺϥϯλΠϜ্Ͱͷ࣮ߦ࣌ʹpiyo͕undefinedʹͳΔͷͰΤϥʔ͕ى͖Δ return x.piyo.split(",") } var foo = {} as Foo // Fooͱͯ͠ѻ͑ΔΑ͏ʹ͓ͯ͘͠ // ࣮ࡍʹbarͳͲແ͍͕Fooͱͯ͠Ξαʔγϣϯ͍ͯ͠ΔͷͰͤΔ something(foo) #hatenaintern -
const as as const ( readonly ) const a =
[1, 2, 3] // aͷܕnumber[]ͱͳΔ const b = [1, 2, 3] as const // bͷܕreadonly [1, 2, 3]ͱͳΔ type Pallet = { colors: readonly Color[] } const setPallet = (p: Pallet) => { /* do something */ } const pallet = { colors: ["red"], } // ͜͜ʹ as const Λ͚ͳ͍ͱ{ color: string[] }ͱਪ͞ΕͯΤϥʔʹͳΔ setPallet(pallet) #hatenaintern -
any ˝ ⛰־ס⡁ֿ⪌זיַ׆כ炐նundefined־؛هةؘؠ ع־꞊丗ױך⛰ֿ⪌זיַי荁ַնtscֿ㑔ס吾錞םַ סךյas⺱喋מ鹴ׄ㕙⺬ע鹴ׄն let anything: any = {}
// anyʹԿͰೖͰ͖Δ anything = () => {} anything = null anything.split(",") // anyͷ߹ϝιουͳΜͰࢀরͰ͖Δ #hatenaintern -
unknown any any unknown unknown {} | null | undefined
const getObjectValues = (obj: {}) => Object.values(obj) // ݺͼग़͠ଆunknownͳͷͰ͖ͳΛͤΔ const stringifyForLog = (val: unknown) => { if (val === null || val === undefined) return "(anonymous)" return JSON.stringify(getObjectValues(val)) } #hatenaintern -
typeכinterface ˝ typeעؙؕٛؓت ˝ interfaceע؛هةؘؠعמ㑔♀ׄ⮯ס亠嫎ն ˝ 仴㰆ססמ䏲־وٞقطؔ鴑ⱶך׀סעinterface ˝ ٚؕهֿٚٛ䬠❠גinterface⮵榫縖ֿ舅榺מ䦡䍖ך׀ ˝
typeע⮯ס⺲⯥♀ׄ䑒釐ֵֿ ˝ typeכinterfaceס✳ַ⮆ׄעؤ٭غ釨硜םלך荇չם孱孬╚䍖ֵֿ סךյ齁מ⪌ף齁מ䏼זיׂדַ #hatenaintern -
typeכinterface Type Type type Blog = { title: string content:
string } // NG: Duplicate identifier 'Blog'. type Blog = { tags: string[] } // OK type NewBlog = Blog & { tags: string[] } Interface Interface ES Array at() TypeScript . Array // lib.es5.d.ts interface Array<T> { length: number toString(): string ... } // lib.es2022.array.d.ts interface Array<T> { at(index: number): T | undefined } #hatenaintern -
꞊丗 仴מئ٤وٜךע⛰䈱⭳י׀יַׄלյ䌕丗鲭⡁ס㑔ס傴׀亠סقذ٭٤גה磆☭יֽ׀ױն const f = (x: string): number => {
return x.length } // ಛʹreturnΛ͠ͳ͍߹ฦΓʹvoidΛࢦఆ͢Δ const a: () => void = () => { console.log("a") } // ΦϓγϣφϧͳҾkeyʹ?Λ͚Δ // ਪ͞ΕΔͷͰྑ͍ͳΒฦΓͷܕলུՄ const b = (n?: number) => `${n}` // Rest ParametersΛड͚औΔ߹͜͏͍͏ײ͡ const c = (...texts: string[]) => { return texts.join("|") } #hatenaintern -
(Generics) TypeScript querySelector - Hatena Developer Blog const getJSON =
<T>(url: string): Promise<T> => { // res.jsonanyͱͳΒͣʹܕҾͰ͞Εͨͷͱղऍ͞ΕΔ return fetch(url).then<T>((res) => res.json()) } // ͜͜ͰusersUser[]ʹͳΔ const users = await getJSON<User[]>("/api/users") // ͜͜ͰblogsBlog[]ʹͳΔ const blogs = await getJSON<Blog[]>("/api/blogs") #hatenaintern -
: extends / const echo = <T extends string>(text: T):
T => { return text } const a = echo("foo") // a ͷܕ 'foo' const str: string = "foo" const b = echo(str) // b ͷܕ 'string' #hatenaintern -
never never void never never ( ) const infiniteLoop =
(): never => { while (true) {} } strictNullChecking JavaScript undefined #hatenaintern -
never榫ַג禿糵䓪زؘشؠ ˝ never榫ַ׆כך㑔؝٭غםלךס禿糵䓪زؘشؠך׀ type Color = "red" | "yellow" |
"purple" const magical = (color: Color) => { switch (color) { case "red": return "tomato" case "yellow": return "banana" default: // શͯͷcase͕ཏ͞Ε͍ͯΕ͜͜ʹ౸ୡ͢Δ͜ͱͳ͍ // ͜ͷ߹'purple'͕ೖ͞ΕΔՄೳੑ͕͋ΔͷͰɺ੩తղੳ࣌ʹΤϥʔʹͳͬͯݕग़Ͱ͖Δ const val: never = color throw new Error(`"${color}" is not implemented`) } } #hatenaintern -
Readonly / ReturnType ˝ Readonlyע؛هةؘؠع鿥⮛ס釐碛鐆ײ鱮ײ㵠榫מך׀ ˝ ⫋䅯氳מע鸵榫םַ׆כמ嫰䙫 type PersonRo =
Readonly<Person> ˝ ReturnTypeע꞊丗ס鲭⡁㑔כי䐂 type Func = () => string type ReturnVal = ReturnType<Func> // ReturnValstringͱղऍ͞ΕΔ #hatenaintern -
typeof TypeScript JavaScript const hello = () => "hello" type
Func = typeof hello type P = ReturnType<Func> // Pstringͱղऍ͞ΕΔ #hatenaintern -
keyof key union type const config = { checkJs: false,
force: true, } // typeofͰconfigͷܕΛಘͯɺkeyofͰͦͷΦϒδΣΫτͷܕͷΩʔΛྻڍ͢Δ type ConfigKey = keyof typeof config // "checkJs" | "force" const getConfigVal = (key: ConfigKey) => config[key] getConfigVal("ignore") // Τϥʔͱͯ͠ݕग़Ͱ͖Δ #hatenaintern -
Indexed Access Types JavaScript [] typeof keyof JavaScript type Person
= { name: string age: number } type Age = Person["age"] // number const signalColors = ["red", "blue", "yellow"] as const // as const͠ͳ͍ͱstring[]ʹͳΔ // Arrayʹ[number]ͰΞΫηε͢ΔͱྻͷΛྻڍͨ͠ܕΛಘΒΕΔ type Signal = typeof signalColors[number] // 'red' | 'blue' | 'yellow' #hatenaintern -
(Intersection Types) 邾丗ס㑔磝ײ⺬י㑔榟䡗ն❆ֻףٗ٭ا٭ס嘤מ 䑴יٝتَ٤تס㑔㚺ֻ㕙⺬ע׆ַֹֹ䚉ն type Blog = { title: string;
domain: string } type Editor = { editable: true; authority: ["edit"] } type Owner = { editable: true; authority: ["edit", "publish"] } type ResponseForEditor = Blog & Editor type ResponseForOwner = Blog & Owner #hatenaintern -
Conditional Types JavaScript condition ? trueExpression : falseExpression // JavaScriptͷࡾ߲ԋࢉࢠ
// SomeType͕OtherTypeΛຬͨͤTrueTypeΛಘΔ SomeType extends OtherType ? TrueType : FalseType; Overloads declare function getID<T extends boolean>( fancy: T ): T extends true ? string : number const stringReturnValue = getID(true) const numberReturnValue = getID(false) const stringOrNumber = getID(Math.random() < 0.5) #hatenaintern -
Overloads Overloads function request(url: string): Promise<Response> function request(url: string, onlyIsOk:
true): Promise<boolean> function request(url: string, onlyIsOk = false) { const promise = fetch(url) if (onlyIsOk) return promise.then((res) => res.ok) return promise } #hatenaintern -
Overloads ˝ 㓹儖ע湾ׂ傴ׂס✳זיֽׄף荁ַך type f = (x: number) => number
˝ ⺱喋ס׆כ׆סֹמ傴ׄ type f = { (x: number): number } Overloads type func = { (x: number): number (x: string): string } #hatenaintern -
(Virtual) DOM React DOM DOM DOM React DOM DOM UI
key https://ja.reactjs.org/docs/reconciliation.html Document Object Model HTML XML https://zenn.dev/mizchi/books/ c c f cc c b #hatenaintern -
JSX JSX JavaScript <h1 className="hello">My name is Clementine!</h1> React DOM
HTML class className class JavaScript #hatenaintern -
ؠٚتؤ٤َ٭ؾ٤عכ꞊丗ؤ٤َ٭ؾ٤ع React 2 <HelloMessage name="hatena" /> ؠٚتؤ٤َ٭ؾ٤ع class HelloMessage extends
React.Component { render() { return <div>Hello {this.props.name}</div> } } ꞊丗ؤ٤َ٭ؾ٤ع const HelloMessage = ({ name }) => { return <div>Hello {name}</div> } #hatenaintern -
ؠٚتؤ٤َ٭ؾ٤عכ꞊丗ؤ٤َ٭ؾ٤ع ؠٚتؤ٤َ٭ؾ٤عע㵧全氳ם䉬塛ֿ◀㲊יַג״յ꞊丗ؤ٤َ٭ؾ٤ع✳榫׆כ䍚ׂ䫟㝢ױն ؠٚتؤ٤َ٭ؾ٤ع React Error Boundary (Function Component) React Component
React Component React Component null Presenter/View React Component Unit Test #hatenaintern -
Function Component TypeScript TypeScript JSX .tsx () => JSX.Element React.FC
type Props = { name: string } const Welcome: React.FC<Props> = ({ name }) => { return <h1>Welcome {name}</h1> } React Component undefined #hatenaintern -
Props / 1 type Props = { name: string }
const Welcome: React.FC<Props> = ({ name }) => { return <h1>Welcome {name}</h1> } ( ) JSX <Welcome name="John" /> // <h1>Welcome John</h1> #hatenaintern -
React Fragmentמחַי <> </> React Fragment React Component 1 Element
<div> 2 React Component const Component = () => { return ( <> <span>hello</span> <br /> <span>͜Μʹͪ</span> </> ) } key <React.Fragment> </React.Fragment> #hatenaintern -
Function Component Hooks Hooks React . 2019 SFC ( Stateless
Functional Component ) #hatenaintern -
(State) useState use React (Hooks) const Counter = () =>
{ const [count, setCount] = useState(0) const increaseCount = () => setCount((prevCount) => prevCount + 1) return ( <div> Χϯτ: {count} <button onClick={increaseCount}>Χϯτ</button> </div> ) } #hatenaintern -
useState useState() 1 2 setter ( ) setter Component DOM
const [color, setColor] = useState<Color>("red") #hatenaintern -
useState setter ˝ 二ַ⡁峚 const [color, setColor] = useState<Color>("red") const
change2Blue = () => setColor("blue") ˝ 泡⯥ס⡁⮵榫י二ַ⡁婊㲊 const [count, setCount] = useState(0) const increaseCount = () => setCount((prevCount) => prevCount + 1) #hatenaintern -
Component alert const Counter = () => { const [count,
setCount] = useState(0) const increaseCount = () => setCount((prevCount) => prevCount + 1) alert(count) return <div>{/* ུ */}</div> } alert OK #hatenaintern -
useEffectס╈ךalert⽛ש const Counter = () => { const [count, setCount]
= useState(0) const increaseCount = () => setCount((prevCount) => prevCount + 1) useEffect(() => { alert(count) }) return <div>{/* ུ */}</div> } Component Component alert alert alert UI UI Component #hatenaintern -
useEffectכ❣㰆鿥⮛ 2 ❣㰆辐鿥⮛峚 Component useEffect(ҙͷॲཧؔ, []) state useEffect(ҙͷॲཧؔ, [state]) state
Component 2 alert const [countA, setCountA] = useState(0) const [countB, setCountB] = useState(0) useEffect(() => { alert(`conutAͷ͕${countA}ʹߋ৽͞Ε·ͨ͠`) }) useEffect(() => { alert(`conutAͷ͕${countB}ʹߋ৽͞Ε·ͨ͠`) }) countA countB #hatenaintern -
useEffectכ❣㰆鿥⮛ ˝ ❣㰆鿥⮛錃㲊׆כךյאבס❣㰆鿥⮛⫂סַ־ס⡁ֿ㚺催גכ׀סײⰜ⛼榫ֿ⽛צ⭳ֹמ⭳全 const [countA, setCountA] = useState(0) const [countB,
setCountB] = useState(0) useEffect(() => { alert(`conutAͷ͕${countA}ʹߋ৽͞Ε·ͨ͠`) }, [countA]) useEffect(() => { alert(`conutAͷ͕${countB}ʹߋ৽͞Ε·ͨ͠`) }, [countB]) [] Component Component DOM ( ) (mount) DOM (unmount) Hooks #hatenaintern -
useEffectכؠٛ٭٤ػشو ˝ useEffectע꞊丗鲭׆כךאס꞊丗ֿ域סⰜ⛼榫ֿ⽛צ⭳⯥מ㲔车 ˝ ׆⮵榫כⰜ⛼榫סؠٛ٭٤ػشوֿ⭳全 roomIdֿ㚺催כյزٔشعסַ頇鐆寕յ二ַ頇鐆ꝧ㡎❆ useEffect(() => { const
handler = () => { /* ৽͍͠ϝοηʔδΛड͚औͬͨͱ͖ͷॲཧ */ } chat.subscribe(roomId, handler) return () => { chat.unsubscribe(roomId) } }, [roomId]) #hatenaintern -
(Custom Hook) use Hook Hooks Component 1 const useGetStatus =
({ userId }) => { const [status, setStatus] = useState(null) useEffect(() => { const handler = (user) => { setStatus(user.status) } Api.subscribe(userId, handler) return () => Api.unsubscribe(userId, handler) }) return status } #hatenaintern -
Tips Component useState useMemo useEffect useCallback ( ) useEffect useCallback
- uhyo/blog #hatenaintern -
♀ꎰ 儖稴מ⪌⮉ם־זג馐ײ鱮؆ד遨餉鉮鐄מחַי傴 ַיַױն艄⽏ֵֿף鐆؆ךׂדַ氳םؤ٭ػ٭ך ն 泘域 Arrow Function useState state Hooks
useMemo useCallback React Component DOM JavaScript JavaScript JavaScript ( ) #hatenaintern -
thisסتؤ٭وס鷿ַמחַי ˝ function榫ַג꞊丗ס㕙⺬ const person = { name: "chris", say:
function () { setTimeout(function () { console.log(`I'm ${this.name}`) }, 100) }, } person.say() // I'm this window.setTimeout(window ) window https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/ setTimeout#thethisproblem #hatenaintern -
thisסتؤ٭وס鷿ַמחַי Arrow Function const person = { name: "chris", say:
function () { setTimeout(() => { console.log(`I'm ${this.name}`) }, 100) }, } person.say() // I'm chris #hatenaintern -
useState state 二ַ⡁峚כ׀ס蛽כ狌 const [count, setCount] = useState(0) const increaseCount
= () => setCount(count + 1) כיױֹכյ const increaseDouble = () => { increment() increment() } סֹםס⛼זגכ׀מյincreaseDouble⽛؆ך1־㘃ֻםַכַֹ杯霄מ鸿鷔ךֹն #hatenaintern -
꞊丗⫂ס㚺丗تؤ٭وכuseState ❆ֻףյcountֿ5ךֵככ const Component = () => { const [count,
setCount] = useState(0) // ͜͜ͰมcountείʔϓͰݻఆ͞ΕΔ(5) const increaseCount = () => setCount(count + 1) // ↑Ͱݻఆ͞Εͨcount + 1(=6)ΛsetCountʹ͢ const increaseDouble = () => { increment() // ↑Ͱ࡞ͬͨؔΛݺͿͱɺ6͕setCountʹ͞ΕΔ increment() // ͜ͷؔΛݺͿͱ͖ɺ6͕setCountʹ͞ΕΔͷͰɺ6ͷ·· } } #hatenaintern -
ؤ٭ٜفشؠ꞊丗峚亠嫎ך傴׀泡 ❆ֻףյcountֿ5ךֵככ const Component = () => { const [count,
setCount] = useState(0) // ͜͜ͰมcountείʔϓͰݻఆ͞ΕΔ(5) const increaseCount = () => setCount((prevCount) => prevCount + 1) // prevCountݺͼग़࣌͠ͷલͷ const increaseDouble = () => { increment() // ͜͜ͰݺͿͱɺprevCountʹ5͕ೖ͍ͬͯΔͷͰɺprevCount+1=6͕setCount͞ΕΔ increment() // ͜͜ͰݺͿͱɺprevCountʹ6͕ೖ͍ͬͯΔͷͰɺprevCount+1=7͕setCount͞ΕΔ } } state #hatenaintern -
Hooks === Object.is const a = "foo" const b =
"foo" console.log(a === b) // true const objA = { a: "foo", b: 10 } const objB = { a: "foo", b: 10 } console.log(objA === objB) // true console.log(Object.is(objA, objB)) // false #hatenaintern -
❣㰆鿥⮛מ؛هةؘؠع⪌آ٭تמחַי const config = { theme: "sports" } useEffect(() =>
{ loadConfig(config).then(() => {}) }, [config]) config [config.theme] #hatenaintern -
ب٤وٜם㍑鹴瓀 Component const config = { theme: "sports" } function
Component() { useEffect(() => { loadConfig(config).then(() => {}) }, [config]) } Props #hatenaintern -
useMemo useMemo React Hooks 1 Component function WordCount({ children })
{ // textstringͳͷͰɺͦͷ··ґଘྻʹग़དྷΔ const words = useMemo(() => children.split(" "), [text]) useEffect(() => { alert(`୯ޠ${words.length}Ͱ͢`) }, [words]) } Component children <WordCount>Lorem ipsum dolor sit amet</WordCount> #hatenaintern -
useCallbackך꞊丗ْٓ ˝ ⡁⺱喋מ꞊丗ْٓגַ㕙⺬עuseCallback⮵榫 ˝ ْٓםַכ夵ٝ٤رٛ٤ء侇מ꞊丗؛هةؘؠعֿ榟䡗 יױֹ const handler = useCallback((val)
=> alert(val), []) useEffect(() => { Api.notification.subscribe(handler) }, [handler]) #hatenaintern -
useMemouseCallback榫ַגقنؚ٭ُ٤ ت䷉ャ ˝ useMemouseCallbackע⡁꞊丗סْٓמזיuseEffectםלס┘釐ם⽛צ⭳䤰⯆׆כמזיقنؚ٭ُ٤ت ס䷉ャ僿䏨ך׀ ˝ 攐מuseMemoךע❣㰆מ✳םַ㕙⺬ךյ⭚杼סꄆַ銶畀磵冽ْٓ׆כךٝ٤رٛ٤ء侇סهٞشؠ䤰ֻ׆כ ⭳全 function Component
({a, b}) => { const resultA = useMemo(() => superDuperHighCostCalculation(a), [a]); const resultB = useMemo(() => superDuperHighCostCalculation(b), [b]); return <> <span>{a}͔ΒʮΊͪΌͪ͘Όॏ͍ܭࢉʯΛͨ݁͠Ռ: {resultA}</span> <span>{b}͔ΒʮΊͪΌͪ͘Όॏ͍ܭࢉʯΛͨ݁͠Ռ: {resultB}</span> </> } #hatenaintern -
React Component DOM React ref useRef ref current const textInput
= useRef(null) const submit = (e) => { e.preventDefault() if (textInput.current.value.length < 100) return alert("101จࣈҎ্͕ඞཁͰ͢") createPost({ body: textInput.current.value }) } return ( <form onSubmit={submit}> <input type="text" ref={textInput} /> </form> ) #hatenaintern -
DOM DOM React const [text, setText] = useState("") const submit
= (e) => { e.preventDefault() if (text < 100) return alert("101จࣈҎ্͕ඞཁͰ͢") createPost({ body: text }) } return ( <form onSubmit={submit}> <input type="text" onChange={(e) => setText(e.target.value)} /> </form> ) #hatenaintern -
TypeScript TypeScript JavaScript tsc babel JavaScript JavaScript API babel poly
ll TS JS babel JavaScript JavaScript webpack JavaScript (bundle) ES Modules 1 JavaScript JavaScript(+sourcemap) minify TS/JS sourcemap 1 webpack Terser TreeShaking #hatenaintern -
create-react-app React OK webpack, babel, eslint npm start npm test
react-scripts create-react-app React create-react-app React #hatenaintern -
JavaScript ( ) JavaScript DOM HTML CSS API ECMAScript WHATWG
HTML Living Standard WHATWG DOM Living Standard W C CSS Speci cations #hatenaintern -
ECMAScript JavaScript ECMAScript Ecma International Technical Committee TC https://github.com/tc /ecma
Living Standard 6 ECMAScript babel tsc poly ll Ecma International C# #hatenaintern -
ECMAScript Stage ECMAScript (proposal) Github proposal issue PR TC Stage
⾒ Issue Stage ECMAScript #hatenaintern -
Stage 2 ECMAScript · JavaScript Primer #jsprimer Stage pre x
API 2 JavaScript Google Chrome Node.js V Safari JavaScriptCore Firefox SpiderMonkey Facebook Hermes #hatenaintern -
ECMAScript Stage ECMAScript core-js poly ll babel ECMAScript Open Open
JavaScript ECMAScript #hatenaintern -
JavaScript ECMAScript JavaScript ECMAScript location.assign WHATWG HTML Living Standard document.querySelector
WHATWG DOM Living Standard WHATWG HTML/DOM Living Standard ECMAScript HTML DOM (Node.js ) W C HTML HTML . 399 5 WHATWG 2021 1 29 WHATWG Living Standard W C / : [https://future-architect.github.io/articles/ a/ HTML | ] 2004 Apple Mozilla Opera 3 W C HTML Living Standard #hatenaintern -
WHATWG Google Chrome HTML DOM API Google Chrome Apple Moziila
Chrome : Chrome Platform Status Mozilla : Mozilla Speci cation Positions W C Web Incubator Community Group https://scrapbox.io/pastak-pub/ WebAPI #hatenaintern -
W C CSS Speci cations CSS CSS WHATWG W C
All CSS speci cations #hatenaintern