Adding type safety to object IDs in TypeScript
kravchyk.com
Adding type safety to object IDs in TypeScript
1–10 of 61 posts
Re: Adding type safety to object IDs in TypeScript
#2Re: Adding type safety to object IDs in TypeScript
#3Re: Adding type safety to object IDs in TypeScript
#4Re: Adding type safety to object IDs in TypeScript
#5 type Brand = BaseType & { readonly __brand__: Brand };
type FooId = Brand;
function fooBar(asdf: FooId | 'foobar'): void { }
fooBar will only accept the literal string 'foobar' or a true FooId, but not any arbitrary string. FooId would then come from a function that validates strings as FooIds, or some other part of the app that is an authoritative source for them. Brands extend their BaseType so they can be used anywhere their BaseType is used, but not the inverseRe: Adding type safety to object IDs in TypeScript
#6Re: Adding type safety to object IDs in TypeScript
#7This is pretty close to type branding (newtype wrapping for the Haskell-inclined), though using template literal types is pretty novel. Normal brands look something like this: type Brand = BaseType & { readonly __brand__: Brand }; type FooId = Brand ; function fooBar(asdf: FooId | 'foobar'): void { } fooBar will only accept the literal string 'foobar' or a true FooId, but not any arbitrary string. FooId would then co…
Re: Adding type safety to object IDs in TypeScript
#8This is pretty close to type branding (newtype wrapping for the Haskell-inclined), though using template literal types is pretty novel. Normal brands look something like this: type Brand = BaseType & { readonly __brand__: Brand }; type FooId = Brand ; function fooBar(asdf: FooId | 'foobar'): void { } fooBar will only accept the literal string 'foobar' or a true FooId, but not any arbitrary string. FooId would then co…
Re: Adding type safety to object IDs in TypeScript
#9This is pretty close to type branding (newtype wrapping for the Haskell-inclined), though using template literal types is pretty novel. Normal brands look something like this: type Brand = BaseType & { readonly __brand__: Brand }; type FooId = Brand ; function fooBar(asdf: FooId | 'foobar'): void { } fooBar will only accept the literal string 'foobar' or a true FooId, but not any arbitrary string. FooId would then co…
type Brand = BaseType & { readonly __brand__: Brand };
const FooIdBrand = Symbol('FooId');
type FooId = Brand;
function fooBar(asdf: FooId | 'foobar'): void { }
Using a private shared symbol your authoritative validation/sources can share your brand symbol and no one else can create one without using your validation. Private symbol brands in this way become the closest Typescript gets to "nominal types".Re: Adding type safety to object IDs in TypeScript
#10- Channel IDs always start with C
- User IDs always start with U