<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Iwo Plaza on Medium]]></title>
        <description><![CDATA[Stories by Iwo Plaza on Medium]]></description>
        <link>https://medium.com/@iwoplaza?source=rss-88e819fa0b17------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JOc2sjE1SJF38E21poepDA.png</url>
            <title>Stories by Iwo Plaza on Medium</title>
            <link>https://medium.com/@iwoplaza?source=rss-88e819fa0b17------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:50:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iwoplaza/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Type Safety in WebGPU Applications: The TypeGPU Approach]]></title>
            <link>https://medium.com/swmansion/type-safety-in-webgpu-applications-the-typegpu-approach-5df019ac6a61?source=rss-88e819fa0b17------2</link>
            <guid isPermaLink="false">https://medium.com/p/5df019ac6a61</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[webgpu]]></category>
            <dc:creator><![CDATA[Iwo Plaza]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 09:02:42 GMT</pubDate>
            <atom:updated>2025-04-15T14:02:34.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ora6QBxIHjwn85Hy-DbSA.png" /></figure><p>There are a few GPU-centric frameworks that solve particular problems, e.g., Three.js for 3D graphics and TensorFlow for AI inference. For more custom solutions, or those with stricter hardware requirements, many developers are forced to build from scratch on top of WebGL/WebGPU. This often involves having to implement binary serialization, dealing with raw binary data and sending untyped values between JS and the shader program. This is similar to the frontend and backend relationship in web apps, where both are more often than not separate code-bases with duplicated business logic, and loosely connected with, e.g., a REST API.</p><p>Recent technologies like tRPC or React Server Components blur the line between the client and server, allowing types to flow from one environment to the other, statically verifying that what the client is calling is actually there.<strong> At Software Mansion, we realized this same pattern could be applied to CPU and GPU communication. This is how TypeGPU was born — it’s our TypeScript library that enhances the WebGPU API, enabling type-safe apps that cross the CPU and GPU boundary.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LzadHoNNm8AokRire9OKZA.png" /><figcaption>Diagram showcasing the similarity between the Frontend &amp; Backend relationship, and the GPU &amp; CPU relationship. The trend of end-to-end type safety can be applied to both.</figcaption></figure><p><a href="https://docs.swmansion.com/TypeGPU/"><strong>TypeGPU</strong></a><strong> acts as a bridge between JavaScript and WebGPU, making data encoding and decoding more straightforward. </strong>By leveraging <a href="https://github.com/iwoplaza/typed-binary?tab=readme-ov-file">typed-binary</a>, you can write GPU programs without worrying about byte-level details. You can also easily define complex data types like structs and arrays, while TypeScript automatically validates both incoming and outgoing data. Plus, <a href="https://github.com/wcandillon/react-native-webgpu">TypeGPU is fully compatible with React Native</a>.</p><p>Let’s dive into how it works, how it addresses common limitations of existing solutions, and what’s on our roadmap toward achieving end-to-end type safety on the GPU.</p><h3>Why WebGPU matters</h3><p><strong>WebGPU is a modern, low-level GPU API that’s great for graphics and general computing tasks like video processing or AI inference — definitely a good one to have in your toolkit.</strong></p><p>With its recent availability for React Native, it’s also truly cross-platform, supporting the web, React Native, and even Deno. To use it, you start with JavaScript, where you can dispatch commands, allocate resources, read from and write to GPU memory, and even send arbitrary shader code. This allows the GPU to process tasks in parallel or execute specific instructions.</p><p>But here’s the catch — the API isn’t really built with a type-safe language in mind. It’s designed for JavaScript. When you send WGSL code to the GPU (which is essentially just a raw code string), you then have to interface with it using numeric indices. That means you need to manually keep track of which indices correspond to which resources.</p><p>The actual code sent to the GPU looks something like this:</p><pre>struct Boid {<br>  position: vec3f,<br>  velocity: vec3f,<br>}<br><br>@group(0) @binding(0) var&lt;storage, read_write&gt; boids: array&lt;Boid, 32&gt;;</pre><p>It looks type-safe at first glance — you’ve got a struct called Boid with clearly defined fields, and you know the type of each field: both are vectors housing 3 floating-point numbers. From the JavaScript side, you’d expect this to be bound as a 32-element array of boids.</p><p>But here’s the issue: that type safety disappears the moment you cross from WGSL to JavaScript. You have to manually create a buffer, estimate its size, and remember that it’s a three-element vector. On top of that, all 3-element vectors need to be aligned to 16 bytes which means adding four bytes of padding between each of the array elements. Forgetting this detail can cause unexpected issues, like incorrect colors, with no obvious reason why. And since you can’t just console.log values on the GPU, debugging becomes a real challenge. In the end, you’re left manually constructing byte buffers, which is both tedious and error-prone.</p><h3>Existing solutions and their limitations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O6ZiDKUGSOsGY-imk8D8mw.png" /><figcaption>Three.js &amp; Shadeup</figcaption></figure><p>The most popular 3d-graphics web library is <a href="https://threejs.org/"><strong>Three.js</strong></a>, a high-level abstraction that sidesteps many of these challenges. With it, you can create 3D scenes, objects, and effects without worrying about the low-level details. However, if you need more control, you have to drop down to WebGPU or WebGL, where writing shaders becomes a necessity. Three.js is actively working on a new feature called TSL: a domain-specific language embedded into JS for defining node-graphs that compile into shaders, which is an amazing improvement over the status quo. That being said, it’s not without its drawbacks. The main limitation of Three.js is that it predates TypeScript, so things like type safety or context-aware auto complete were never core design considerations. In addition, mixing local AI inference (e.g., super-resolution) can become quite complex, as frameworks are rarely made to interoperate with each other.</p><p>Another solution is <a href="https://shadeup.dev/"><strong>Shadeup</strong></a>, which addresses some of the same issues we set out to solve with our custom toolkit: TypeGPU. Its author created a custom language that compiles both to JavaScript and WGSL, allowing you to write CPU and GPU code in the same language while maintaining type safety. Shadeup is also modular, meaning you can compose shaders from multiple files. It’s an amazing solution, and we encourage you to try it out yourself, but there were a few things we felt like we could improve on. Having to learn a custom language comes with a steep learning curve — not something most developers are eager to do. On top of that, adopting Shadeup into existing JavaScript and WebGPU projects isn’t the easiest task.</p><h3>How TypeGPU works</h3><pre>// Type-safe schemas<br><br>const Boid = d.struct({<br>  position: d.vec3f,<br>  velocity: d.vec3f,<br>});<br><br>// Initialization<br><br>const root = await tgpu.init();<br><br>const buffer = root.createBuffer(d.arrayOf(Boid, 32)).$usage(&#39;storage&#39;);<br><br>buffer.write(<br>  Array.from({ length: 32 }).map(() =&gt; ({<br>    position: d.vec3f(Math.random(), Math.random(), Math.random()),<br>    velocity: d.vec3f(Math.random(), Math.random(), Math.random()),<br>  })),<br>);</pre><p><strong>With TypeGPU, you define data-types using our typed primitives, mirroring WGSL syntax</strong>. This means you can create a <em>Boid</em> struct with <em>position</em> and <em>velocity </em>fields, just as before.</p><p>Instead of working directly with the WebGPU API, you can use the TypeGPU API to create a typed buffer. The important part is that <strong>TypeGPU keeps track of what data-type the buffer holds, and gives you that information on hover.</strong> This allows JS arrays and objects to be passed directly to the GPU, and TypeGPU will handle their byte representation for you. If there’s a mismatch, like passing something that isn’t a <em>vec3f</em>, the type-checker gives you instant feedback.</p><p>However, there’s still some duplication: the struct exists in both JavaScript and WGSL. That means any changes require manual updates on both sides, which isn’t ideal.</p><p>So, how to tackle the duplication? <strong>The ideal solution would be to represent everything that can be written or expressed in WGSL directly in JavaScript. </strong>With TypeGPU, we’re getting pretty close to that goal.</p><p>We’ve already made significant progress with several releases. Now, you can work with buffers, data types, bind groups, vertex layouts, and more. But there’s still a lot to do. Our roadmap includes implementing a variety of primitives that will allow us to achieve end-to-end type safety on the GPU.</p><h3>The future of TypeGPU</h3><blockquote>The following code snippets showcase experimental APIs, which are accessible in official releases under certain configurations. Refer to our documentation, if you’d like to try them out yourself!</blockquote><p>So, where do we want to be in the not-so-distant future? Let’s analyze this WGSL code:</p><pre>@group(0) @binding(0)<br>var&lt;uniform&gt; factor: f32;<br><br>fn offset(num: f32) -&gt; f32 {<br>  return num + factor;<br>}<br><br>fn scale(num: f32) -&gt; f32 {<br>  return num * factor;<br>}<br><br>@compute @workgroup_size(32)<br>fn main() {<br>  let value = scale(11 + offset(4));<br>  // ...<br>}</pre><p>Here, we have another uniform variable <em>factor</em> that can be provided by JS at runtime. We also have the <em>offset</em> function, which adds <em>factor</em> to the input and returns the result, as well as the <em>scale</em> function which multiplies the input by <em>factor</em>. Additionally, we have the main entry function of the shader, which uses both utility functions.</p><p>So, what would this look like in JS?</p><pre>const layout = tgpu.bindGroupLayout({<br>  factor: { uniform: d.f32 },<br>});<br><br>// We can either implement functions in JavaScript...<br>const offset = tgpu.fn(<br>  { num: d.f32 },<br>  d.f32,<br>)((args) =&gt; {<br>  return args.num + layout.$.factor;<br>  // inferred as:            ^? number<br>});<br><br>// ... or in WGSL<br>const scale = tgpu.fn({ num: d.f32 }, d.f32)`{<br>  return num * layout.factor;<br>}<br>`.$uses({ layout });<br><br>const main = tgpu.computeFn({ workgroupSize: 32 })`{<br>  let value = scale(11 + offset(4));<br>  // ...<br>}<br>`.$uses({ scale, offset });</pre><p>The same bind group layout can be defined as an object with a <em>factor</em> property (similar to <em>var&lt;uniform&gt;</em> <em>factor</em> in WGSL). Binding indices are determined by the order of the fields in the object, so we can skip defining them altogether.</p><p>tgpu is imported directly from the “typegpu” package, and it comes with APIs that will help us define the rest of the shader. tgpu.fn can be used to define a type-safe function signature which you can then implement.</p><blockquote>Notice how we can implement these functions with either WGSL or JavaScript, and both can be referenced in other functions all the same.<strong> This means that you can decide which language to use on a per-function basis, which aids in both progressively migrating your shaders to JavaScript, or granularly ejecting back into WGSL.</strong></blockquote><p>Even though the syntax used inside of TypeGPU functions is 100% valid JavaScript, we call the subset of JS that we support along with our standard library as the <em>TypeGPU Shading Language</em> (<strong>TGSL</strong>).</p><p>For WGSL-implemented functions, pass in any external values via the$uses(…) method (in this case, the bind group layout or any other functions).</p><p><strong>The great thing about this shader is that it’s composed of JS values. This means you can split them up, organize them into different files or modules, and make your shader code automatically modular. </strong>To resolve it into its WGSL form (so you can send it to the GPU) you can use the tgpu.resolveAPI. Thanks to our resolution algorithm, you can pass in just the main function, and it will automatically include both its definition and the definitions of all its dependencies.</p><pre>// Returns a string of raw WGSL, containing<br>// `main`, `scale`, `offset` and `factor`.<br>const rawWgsl = tgpu.resolve({ externals: { main } });</pre><p>Now, since we generate WGSL from JavaScript, you might wonder: <strong>is it possible to go the other way and generate JavaScript from WGSL? The answer is yes! </strong>That’s exactly why we created a package called <a href="https://www.npmjs.com/package/tgpu-gen">tgpu-gen</a>, which allows you to generate elements like buffers, bind groups, and data types from an existing WGSL shader.</p><p>You can use the package like this:</p><pre>npx tgpu-gen **/*.wgsl           # for migration!<br>npx tgpu-gen **/*.wgsl --watch   # as a codegen step!</pre><p>So, if you’re looking to migrate from a WebGPU app, you can simply use the resulting files and continue working with them as you normally would. Alternatively, if you prefer to write WGSL but still want the type safety, you can use it as a codegen step. Every time you make changes to your WGSL code, it’ll automatically regenerate the corresponding JavaScript in the background.</p><h3>3 ways to incorporate TypeGPU into your workflow</h3><p>Let’s explore some example use cases of how TypeGPU can fit into your workflow. There are three main scenarios:</p><ol><li>“I want to use TypeGPU in my existing WebGPU project”</li><li>“I want to call the xyz utility function from my shader without the full migration”</li><li>“I want to create a fully type-safe GPU program from scratch”</li></ol><p>For the first use case, if you already have a WGSL shader (a file with your shader code), you can run npx tgpu-gen to generate the equivalent JavaScript for it, all while continuing to use your original shader code beneath the surface. This allows you to gradually adopt TypeGPU in your project without a full-scale migration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHgghNywDdF9fD0bC4OCeA.png" /></figure><p>If you’re interacting with the program after it’s been dispatched, you can simply use the generated JavaScript primitives. For example, you can import the shader code and the relevant structures — like the Boid struct — and then create a buffer directly from the imported types.</p><p>For the second use case, “I want to call the XYZ utility function from my shader without the full migration,” we can utilize TypeGPU’s linking capabilities. Instead of using the shader code directly, we use it as a <em>template</em>, and give TypeGPU all external dependencies it needs to include in the final shader code. This way, you can use utility functions coming from external packages without a full migration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3G82HzUfgv_ite4o8wp3Wg.png" /></figure><p>Finally, it’s time for the last use case: creating a fully type-safe GPU program from scratch. <strong>With TypeGPU, you can write all your code directly in JavaScript or TypeScript, making your codebase more unified &amp; consistent</strong>. This means you can move seamlessly between CPU and GPU logic, relying on TypeScript to ensure type safety, which simplifies the process and keeps your workflow more straightforward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DtMxBGUZh9dHW3YwTl1Idg.png" /></figure><h3>There’s more to come</h3><p>Unlike other libraries that are tailored for specific use cases, <strong>TypeGPU provides a lightweight, type-safe layer on top of WebGPU that gives you the flexibility to use only what you need.</strong> Instead of offering a full-fledged GPU implementation for a particular domain, we focus on providing a minimal, core API that you can extend with additional modules.</p><p>With TypeGPU, you don’t have to worry about integrating a huge framework. Instead, you just include the core essentials and add the modules you need, which makes GPU programming easier and saves you from having to learn a new language.</p><p>So far, TypeGPU supports essential features like buffers, data types, and bind groups, but this is just the beginning. Our roadmap includes:</p><ul><li>Providing typed pipelines to ensure shader stages match and pipeline constants are filled with correct values.</li><li>Wrapping functions in a “typed shell” to enable movement across different files/modules.</li><li>Enabling writing imperative shader code in TypeScript, using TypeScript’s LSP to bridge the gap between our API and type-safe shader code.</li></ul><p>We’re planning to add more modules, like AI inference utilities and noise generators, and we’re looking forward to community contributions along the way, so stay tuned for more!</p><p>Prefer the video format? Check out the recording from one of our RNCK meetups:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDysmnC1D2gQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDysmnC1D2gQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDysmnC1D2gQ%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1967417b98eb86af36263ced8ef8b43c/href">https://medium.com/media/1967417b98eb86af36263ced8ef8b43c/href</a></iframe><p>We’re Software Mansion: multimedia experts, AI explorers, React Native core contributors, community builders, and software development consultants. Hire us: <a href="/service/mailto:projects@swmansion.com">projects@swmansion.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5df019ac6a61" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swmansion/type-safety-in-webgpu-applications-the-typegpu-approach-5df019ac6a61">Type Safety in WebGPU Applications: The TypeGPU Approach</a> was originally published in <a href="https://medium.com/swmansion">Software Mansion</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I tricked myself into making a type-safe binary manipulation library]]></title>
            <link>https://medium.com/@iwoplaza/i-tricked-myself-into-making-a-type-safe-binary-manipulation-library-59cbce302c03?source=rss-88e819fa0b17------2</link>
            <guid isPermaLink="false">https://medium.com/p/59cbce302c03</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Iwo Plaza]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 20:35:17 GMT</pubDate>
            <atom:updated>2024-03-01T20:35:17.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*y7z2xx_nQxc2d9yIw7qReQ.gif" /></figure><p>Rarely do TypeScript developers have to interact with binary data directly. We can usually depend on abstractions or ready-made solutions, but where is the fun in that? I thought to myself:</p><blockquote>“What is the most TypeScript way of interacting with binary?”</blockquote><p>With the release of <a href="https://github.com/iwoplaza/typed-binary">Typed Binary 4</a>, it seems to be the best time to go through how the library has helped me (and hopefully can help you) confidently tackle binary-specific problems in TypeScript.</p><h4>Binary data in TypeScript</h4><p>Whether to decode/encode custom file formats, talk to a game server across the network or run code on the GPU, we eventually go down to the level of <em>*just binary*</em>. Having to interact with binary data in a TypeScript code-base can be a daunting task, even with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Typed_arrays">typed arrays</a>. Add on the complicated alignment rules of the <a href="https://www.oreilly.com/library/view/opengl-programming-guide/9780132748445/app09lev1sec2.html">std140</a> standard, and the thought of debugging whether the GPU correctly interprets our Minecraft clone voxel grid is… not fun. <strong>There has to be a better way.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tt-19xDhwnVOvMHgWTCldA.png" /></figure><h4>A good set of primitives</h4><p>Lets start off with the basics. We can encode binary primitives into serial streams, and read them back.</p><pre>import { BufferWriter, u32, f32 } from &#39;typed-binary&#39;;<br><br>// We can either staticly enforce a maximum buffer size, or<br>// use size estimation (shown later)<br>const buffer = new ArrayBuffer(8);<br><br>// Anything that implements the ISerialOutput interface can be<br>// written to. The built in BufferWriter operates on ArrayBuffers.<br>const output = new BufferWriter(buffer);<br><br>u32.write(output, 500);<br>f32.write(output, 9.5);</pre><p>Then when we want to read the data back, we can do the same sequence and replace <em>writes</em> with <em>reads</em>.</p><pre>const input = new BufferReader(buffer);<br>const id = u32.read(input); // 500<br>const health = f32.read(input); // 9.5</pre><blockquote>If you care about consistent byte order across devices (you usually should), <a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> can be set explicitly when creating a BufferWriter/BufferReader. By default it is set to the automatically detected system endianness.</blockquote><p>There are many primitives built into the language, but we can extend the usefulness of them with <strong>compound schemas</strong>.</p><h4>Representing compound data</h4><p>Instead of writing and reading a set of primitives to build up bigger structures, we can use compound types like <strong>objects</strong>, <strong>tuples</strong> or <strong>arrays</strong>.</p><pre>import { object, dynamicArrayOf, string, u32, f32 } from &#39;typed-binary&#39;;<br><br>// properties are encoded next to each other in the<br>// order they are defined in the schema.<br>const Player = object({<br>  id: u32,<br>  name: string, // a null-terminated string<br>  health: f32,<br>  position: tupleOf([f32, f32, f32]),<br>    // length of the array gets encoded into the binary,<br>    // therefore supporting a variable-length array.<br>    inventory: dynamicArrayOf(object({<br>    id: u32,<br>    quantity: u32,<br>  })),<br>});<br><br>const player = {<br>  id: 500,<br>  name: &#39;Dave&#39;,<br>  health: 9.5,<br>  position: [0.1, 12.0, 16.7],<br>  inventory: [],<br>} as const;<br><br>// Creating a buffer that is sized &quot;just enough&quot; to hold a<br>// single player.<br>const buffer = new ArrayBuffer(Player.measure(player).size);<br><br>// The function only accepts values that match the schema.<br>Player.write(new BufferWriter(buffer), player);</pre><p>Compound schemas are made in a way that allows TypeScript to infer what value the binary actually represents in terms of JavaScript values. We can extract what value is encoded by the schema using the `<em>Parsed</em>` utility type:</p><pre>type Player = Parsed&lt;typeof Player&gt;;<br><br>expectTypeOf&lt;Player&gt;().toMatchTypeOf&lt;{<br>  id: number;<br>  name: string;<br>  health: number;<br>  position: [number, number, number];<br>  inventory: { id: number, quantity: number }[];<br>}&gt;();</pre><p>This further reduced the amount of errors I was making when transitioning between <strong>typed</strong> values and <strong>raw binary</strong>.</p><h4>My favorite feature</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jHKpaiYsAS_UNPX7JCP2aQ.png" /></figure><p>The initial use case for this library required the presence of <strong>recursive</strong> schemas. Lets see an example of what I mean. How would you define a schema that supports the following value:</p><pre>const expr = {<br>  type: &#39;add&#39;,<br>  left: {<br>    type: &#39;literal&#39;,<br>    value: 123,<br>  },<br>  left: {<br>    type: &#39;multiply&#39;,<br>    left: {<br>      type: &#39;literal&#39;,<br>      value: 0.2,<br>    },<br>    right: {<br>      type: &#39;literal&#39;,<br>      value: 6,<br>    },<br>  },<br>};</pre><p>Seems easy enough, lets try using <strong>generic</strong> schemas to do so:</p><pre>const Expr = generic({<br>  /* common properties, none in this example */<br>}, {<br>  // a &#39;literal&#39; sub-type<br>  &#39;literal&#39;: {<br>    value: f32,<br>  },<br>  // an &#39;add&#39; sub-type<br>  &#39;add&#39;: {<br>    left: Expr,<br>    right: Expr,<br>  },<br>  // a &#39;multiply&#39; sub-type<br>  &#39;multiply&#39;: {<br>    left: Expr,<br>    right: Expr,<br>  },<br>});</pre><p>We would expect this to work by default, but unfortunately, this recursive definition prohibits TypeScript from properly inferring the type of this schema.</p><p>In order to have working type inference, we need to introduce some <em>indirection</em>.</p><pre>// The `keyed` schema associated the given key (&#39;expr&#39; in this<br>// case) with the schema that gets returned from the function <br>// in its second parameter.<br>//<br>// The &#39;Expr&#39; parameter, which was named just like the<br>// resulting schema to draw a parallel between them, is<br>// just a reference to the schema that will be returned.<br>const Expr = keyed(&#39;expr&#39;, (Expr) =&gt;<br>  generic({<br>    /* common properties, none in this example */<br>  }, {<br>    // a &#39;literal&#39; sub-type<br>    &#39;literal&#39;: {<br>      value: f32,<br>    },<br>    // an &#39;add&#39; sub-type<br>    &#39;add&#39;: {<br>      left: Expr,<br>      right: Expr,<br>    },<br>    // a &#39;multiply&#39; sub-type<br>    &#39;multiply&#39;: {<br>      left: Expr,<br>      right: Expr,<br>    },<br>  }),<br>);</pre><p>The references are resolved when parsing the value of a keyed schema (using the `<em>Parsed&lt;T&gt;</em>` utility type). If the “how” of this mechanism interests you, <strong>let me know in the comments</strong>! I will make a follow-up post about the inner-workings of <em>Typed Binary</em>.</p><h4>Extend to your heart’s content</h4><p>I wanted to make sure that the built-in primitives and schemas support 90% of use-cases out of the box, but what if I needed to encode a JS object as a list of key-value pairs? In the case of WebGPU integration, all struct values have to adhere to specific alignment rules, not tightly packed as it is by default.</p><p>Lets see a simple example of implementing a custom schema that encodes an angle in radians with 2 bytes of precision.</p><pre>/**<br> * A schema storing radians with 2 bytes of precision.<br> */<br>class RadiansSchema extends Schema&lt;number&gt; {<br>  read(input: ISerialInput): number {<br>    const low = input.readByte();<br>    const high = input.readByte();<br>    const discrete = (high &lt;&lt; 8) | low;<br>    <br>    return (discrete / 65535) * Math.PI;<br>  }<br>  write(output: ISerialOutput, value: number): void {<br>    // The value will be wrapped to be in range of [0, Math.PI)<br>    const wrapped = ((value % Math.PI) + Math.PI) % Math.PI;<br>    <br>    // Clipping the value to be ints in range of [0, 65535]<br>    const discrete = Math.min(Math.floor((wrapped / Math.PI) * 65535), 65535);<br>    const low = discrete &amp; 0xff;<br>    const high = (discrete &gt;&gt; 8) &amp; 0xff;<br><br>    output.writeByte(low);<br>    output.writeByte(high);<br>  }<br>  measure(<br>    _: number | MaxValue,<br>    measurer: IMeasurer = new Measurer(),<br>  ): IMeasurer {<br>    // The size of the data serialized by this schema<br>    // doesn&#39;t depend on the actual value. It&#39;s always 2 bytes.<br>    return measurer.add(2);<br>  }<br>}<br><br>export const radians = new RadiansSchema();</pre><h4>Final remarks</h4><p>Thank you for reading this far! Hope you found <a href="https://github.com/iwoplaza/typed-binary">Typed Binary</a> interesting, let me know your first impressions and thoughts about using it in the comments 💚🐸</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59cbce302c03" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>