#strongTyping

2025-11-12

I have a script called pyfix which runs mypy and ruff to

- have strong typing
- have a fixed and orderly import order
- have the file always formatted in the same way
- detect programming errors and redundancies.

Now I am working on gitlogui (codeberg.org/harald/gitlogui) the main script of which I called glu. So I am running

pyfix glu

all the time, which reads funny. 😀

#python #gitlogui #mypy #ruff #strongTyping #linting

2025-11-11

Nice one. Type hints in Python allow to list a number of literal values, similar to TypeScript union types and the syntax is actually somewhat more explicit.

To implement page up/down in codeberg.org/harald/gitlogui I have now:

def doPage(self, factor: Literal[-1] | Literal[1]) -> None:
step = factor * int(self.pageSize.get())
...

and I can be sure, when using mypy, that doPage is only ever called with either -1 or 1.

#python #typehint #strongTyping #gitlogui

2025-10-27

Grmbl.😩

Implementing an object graph with with loops.

After setup, it needs additional initialization.

The fields getting set will not change again. Ideally would be final (Java, or readonly in TypeScript). And I don't want an "if (bla!=null)" where ever access I them.

In my ideal solution this would be guarded by the type system where the nodes, once initialized, change type. I know roughly how it could be done, but its weird and cumbersome. 😕

#Java #final #datastructure #strongTyping

2025-05-27

#programming #engineering #types #strongTyping #commonLisp #example screwlisp.small-web.org/progra for my friend @aleteoryx .

Actually the #historicalNotes in the first paragraph of this article are a little explored key frontier in #computerScience , but the strong typing examples are simple ( etypecase and deftype.. satisfies for those in the know).

I am personally still figuring out how typing in this manner does and can further connect to #typeTheory.

2025-05-15

Theory: the world's infatuation with weakly typed languages was exacerbated because the bastion of compile-time #strongtyping was #microsoft... and MS *sucks* at it! They switched their mvc json parser from newtonsoft to something that only works sometimes.. you want to have a configurable webhook? Be ready for the fact that `System.Net.Http.HttpMethod` is a class and not an enum. Solely so that you can give a non-compliant string as your http method. There *are* verbs enums... buried elsewhere. *and*, when youre trying to call your configurable webhook, *surprise*! The "request" object knows what headers ought to be on a different type (i.e., "content"), and throws an exception if you give it a header it finds unappetizing. fucking.... whyyyyyyy? This is creating types because you can, not because they need to exist!

2025-02-10

Just updated the Database App Modules tutorial in the Kitten documentation to fix a few bugs, update to latest Kitten syntax, and improve the instructions:

kitten.small-web.org/tutorials

(Database app modules are special app modulesš that let you create strongly-typed JavaScript databases² in your Small Web³ apps.)

Enjoy!

:kitten:💕

š kitten.small-web.org/reference
² codeberg.org/small-tech/jsdb#r
Âł ar.al/2024/06/24/small-web-com

#Kitten #DatabaseAppModules #AppModules #tutorial #SmallWeb #SmallTech #web #dev #JSDB #JavaScriptDatabase #JavaScript #database #web #dev #NodeJS #strongTyping

Strengthening Input Validation with Branded Types in TypeScript

804 words, 4 minutes read time.

TypeScript offers numerous advantages in building safer, more reliable code, and one advanced but highly effective approach is branded types. If you work with strings in TypeScript, particularly when validating inputs like email addresses or formatted IDs, you’ve likely encountered the challenge of distinguishing specific formats. Branded types bring a way to enforce stronger validation and add clarity to your TypeScript code without sacrificing flexibility. Inspired by Andrew Burgess’s insights in his video Branded Types Give You Stronger Input Validation, this blog will break down the branded type pattern and its applications.

What Are Branded Types?

In TypeScript, branded types allow you to attach a unique identifier to specific string formats, helping differentiate between regular strings and strings that must adhere to particular formats—like email addresses, product IDs, or dates. Although branded types can work with numbers or other primitives, they’re especially useful with strings.

Imagine a function called sendWelcomeEmail designed to send emails to new users. Normally, we might define the email parameter as a simple string, but this allows any string to be passed, even if it doesn’t resemble a valid email address. Branded types solve this by creating a custom type that isn’t directly assignable from regular strings, requiring validation first.

How to Create a Branded Type in TypeScript

Creating a branded type is relatively simple. Instead of defining a type alias as a basic string, you create a type that’s an intersection of string and an object with a unique “brand” property. Here’s a sample implementation for an EmailAddress branded type:

type EmailAddress = string & { __brand: "EmailAddress" };

Here, EmailAddress is a string with a unique brand that makes it distinct from other strings. The branded type requires validation before assignment, ensuring that any EmailAddress passed around the system has been verified.

Validating Branded Types with Type Guards

To validate branded types, you’ll need a type guard function to check the format of the input string and “brand” it if it passes. In TypeScript, we define this with a function that returns a type predicate. Below is an example function isEmailAddress that checks if a string includes @gmail.com (for simplicity) and returns a branded EmailAddress type if it does.

function isEmailAddress(email: string): email is EmailAddress {    return email.includes("@gmail.com");}

This function validates the email and then “brands” it, letting TypeScript know that we consider this string a genuine EmailAddress. While this example is basic, you could expand it using regex or other validation rules.

Why Use Branded Types?

Branded types provide robust input validation without the need for constant re-validation. By using branded types at the boundaries of your application—such as at the point where user input enters the system—you can validate and brand the inputs, safely passing them around as trusted values. This results in several key benefits:

  1. Increased Reliability: Once a value is branded, you know it has passed specific validation criteria.
  2. Reduced Risk of Bugs: Reduces the chance of invalid data being processed or causing errors down the line.
  3. Code Readability: When you see EmailAddress instead of string, you know instantly what data is being handled.
  4. Enhanced Security: By enforcing validation at the edges of your application, you prevent potentially harmful data from circulating within your system.

Asserting Branded Types

Another way to validate branded types is with assertions. Assertions allow us to throw errors when validation fails, which can be particularly helpful for critical data. Here’s an example of an assertion function for our EmailAddress type:

function assertEmailAddress(email: string): asserts email is EmailAddress {    if (!email.includes("@gmail.com")) {        throw new Error("Invalid email address format");    }}

This function throws an error if the email doesn’t match the expected format. Assertions are especially useful when you need immediate error feedback, such as in input validation for API endpoints or user input.

A Practical Use Case: The SignUp Function

Imagine you’re building a sign-up system where the user provides an email address. Here’s how you might use branded types to ensure that only validated emails are passed to your functions:

function signUp(email: string) {    assertEmailAddress(email);    sendWelcomeEmail(email); // Now considered a validated EmailAddress}

By calling assertEmailAddress early, we ensure that sendWelcomeEmail only receives valid email addresses, adding a layer of safety to our application.

Advantages of TypeScript with Branded Types for Security and Safety

TypeScript’s branded types offer developers the best of both worlds: strong type checking and safe, validated data. With TypeScript’s support for sophisticated type constructs, branded types are especially powerful tools for ensuring that input data meets system expectations.

Using branded types at scale improves both code reliability and security. As noted by Andrew Burgess, “Branded types are a great way to use TypeScript and input validation together to make a stronger, safer system.” This insight underscores the utility of branded types for applications where validated data is essential to system integrity and security.

D. Bryan King

Related Posts

Rate this:

#brandedTypes #codeSafety #dataIntegrity #emailValidation #emailValidationTypeScript #inputValidation #programming #secureCoding #secureInputValidation #strongTyping #typeChecking #TypeScript #TypeScriptAdvancedPatterns #TypeScriptAssertions #TypeScriptBestPractices #TypeScriptBlog #TypeScriptBrandedTypes #typescriptCodingTechniques #TypeScriptDataValidation #TypeScriptEmail #TypeScriptIntersections #TypeScriptPatterns #TypeScriptSecurity #TypeScriptTutorial #TypeScriptTypeGuards #TypeScriptValidation

2023-10-05

A well written article, worth reading regardless of the camp you’re in.
svix.com/blog/strong-typing-hi
#strongtyping #typescript #javascript

Infinite State MachinetPl0ch
2023-09-07

To all advocates:

also have

Sincerely,
Me

Client Info

Server: https://mastodon.social
Version: 2025.07
Repository: https://github.com/cyevgeniy/lmst