w ͳͷͰυΩϡϝϯ τʹͪΌΜͱ5ZQF"MJBTFTͱॻ͔Ε͍ͯΔ https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases w ਓؒʹผ໊Ͱ͋Δ͜ͱࣝผͰ͖Δ͕ ίϯύΠ ϥʹstringʹผ໊Λ͚ͨ͜ͱ͔͠Θ͍ͬͯͳ͍ w UserIdͱBookId͕ޓ͍ʹstringͷผ໊Ͱ͋Δͱ͍͏͚ͩͰ ͦΕΒ͕ޓ͍ʹ۠ผ͞Ε͏ Δ͖ͱ͍͏ཁ݅·ͰίϯύΠ ϥʹΘ͍ͬͯͳ͍
w ͜ΕυΩϡϝϯ τʹهࡌ͞Ε͍ͯΔ https://www.typescriptlang.org/docs/handbook/type-compatibility.html w ܕ໊ͷҧ͍͚ͩͰܕ͕ҟͳ͍ͬͯΔͱผ͢Δํࣜ/PNJOBM5ZQJOHͱ͍͏ w 5ZQF4DSJQUͪ͜Βͷํࣜ࠾༻͍ͯ͠ͳ͍
Argument of type 'UserId' is not assignable to parameter of type 'BookId'. Property 'bookId' is missing in type 'UserId' but required in type 'BookId'.(2345) Τϥʔʹͳͬͯ ͘Εͨ
τͱͷަࠩܕ & ʹ͢Δ͜ͱͰϦςϥϧͷ·· ۠ผͰ͖ΔΑ ͏ʹ͢Δ w ਖ਼֬ͳग़యൃݟͰ͖͍ͯͳ͍͕ෳͷจݙ͋Γ w #SBOEFE5ZQFTͱݺΕ͍ͯΔ͕ ʮ/PNJOBM5ZQJOHΛ࣮ݱ͍ͨ͠ͷ͔ͩΒʯ ͱ͍͏҆ͳຊਓతޠ๏Ͱ ࠓճNominal<T, U>ͱͨ͠ export type Nominal<T, U extends string> = T & { __brand: U };
__brand: U }; type BookId = Nominal<string, 'BookId'>; type UserId = Nominal<string, 'UserId'>; const id = 'ckyx6c8xc000009jm8acefv2v' as UserId; const result = await fetchBook(id); Argument of type 'UserId' is not assignable to parameter of type 'BookId'. Type 'UserId' is not assignable to type '{ __brand: "BookId"; }'. Types of property '__brand' are incompatible. Type '"UserId"' is not assignable to type '"BookId"'.(2345) ͪΌΜͱ۠ผͰ͖͍ͯΔ
U }; type BookId = Nominal<string, 'BookId'>; type UserId = Nominal<string, 'UserId'>; const id = 'ckyx6c8xc000009jm8acefv2v' as UserId; const result = await fetchBook(id); ʮͰBTېࢭͯ͠·ͤΜͰͨ͠ ʁ ʯ
return typeof v === 'string'; } export function assertString(v: unknown, target = ''): asserts v is string { if (!isString(v)) { throw new Error(`${target} should be string`.trim()); } } ͨΓલͷΑ ͏ͳ༰ͷ͕ؔͩɺ unknownܕΛstringܕͱΈͳͨ͢Ίʹɺ Θ͟Θ͟͜͏͍͕ͬͨؔඞཁ
} from './nominal'; type FilledString = Nominal<string, 'FilledString'>; function isFilledString(v: unknown): v is string { return isString(v) && v !== ''; } function assertFilledString( v: unknown, target = '' ): asserts v is FilledString { if (!isFilledString(v)) { throw new Error(`${target} should be not empty string`.trim()); } } type FilledStringΛએݴ͠ɺ ඞۭͣจࣈྻͰͳ͍͜ͱΛද໌͢Δ
BookId)ͱ͍͏γάωνϟ͔ΒಘΒΕΔใྔ͕ fetchBook(id: string)ʹൺ͙ͯͬͱ૿͢ w ͦΕUserIdͰμϝͱΘ͔Δ w ͦΕۭจࣈྻͰμϝͱΘ͔Δ w ࣮୲ऀʹޱ಄Ͱฉ͍ͯճΔඞཁ͕ͳ͍ w ͜ͷߟ͑ํܖϓϩάϥϛϯά ʢ%FTJHOCZ$POUSBDU %C$ͳͲͱʣ ͷ ํ๏ʹج͍͍ͮͯΔ w ಛʹࣄલ݅ෆม݅ʹ֘