Last active
July 13, 2024 19:01
-
-
Save DarkGL/3c8f70a194447d64fad4c3941c8a03cc to your computer and use it in GitHub Desktop.
Disable toLowerCase on already lower cased string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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