Skip to content

Instantly share code, notes, and snippets.

@DarkGL
Last active July 13, 2024 19:01
Show Gist options
  • Save DarkGL/3c8f70a194447d64fad4c3941c8a03cc to your computer and use it in GitHub Desktop.
Save DarkGL/3c8f70a194447d64fad4c3941c8a03cc to your computer and use it in GitHub Desktop.
Disable toLowerCase on already lower cased string
// Step 1: Define the Branded Type
type LowercaseString = string & { __brand: "LowercaseString" };
// Step 2: Type Guard Function
function toLowercaseString(s: string): LowercaseString {
return s.toLowerCase() as LowercaseString;
}
// Step 3: Override Type Definitions
type RemoveToLowerCase<T> = Omit<T, "toLowerCase">;
type SafeLowercaseString = RemoveToLowerCase<LowercaseString>;
// Usage
const normalizedInput: SafeLowercaseString = toLowercaseString("Hello World");
// Trying to call toLowerCase() on normalizedInput will result in a TypeScript error
// normalizedInput.toLowerCase(); // Error: Property 'toLowerCase' does not exist on type 'string & { __brand: "LowercaseString"; }'.
// To use it as a normal string, you need to explicitly cast it back
const normalString: string = normalizedInput as string;
normalString.toLowerCase(); // This is fine, but now it's not type-checked as a lowercase string
/*------------------------------------------------------------------------------------------------------------*/
// Step 1: Define the Branded Type
type SafeLowercaseString = Omit<string, "toLowerCase"> & { __brand: "LowercaseString" };
// Step 2: Type Guard Function
function toLowercaseString(s: string): SafeLowercaseString {
return s.toLowerCase() as unknown as SafeLowercaseString;
}
// Usage
const normalizedInput = toLowercaseString("Hello World");
// Trying to call toLowerCase() on normalizedInput will result in a TypeScript error
// normalizedInput.toLowerCase(); // Error: Property 'toLowerCase' does not exist on type 'string & { __brand: "LowercaseString"; }'.
// To use it as a normal string, you need to explicitly cast it back
const normalString: string = normalizedInput as string;
normalString.toLowerCase(); // This is fine, but now it's not type-checked as a lowercase string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment