1

I would like to have a function that accepts a string, but not "any" string. A string that has been warded.

type AttributeCode = string;
type ItemId = string;

function checkAttributeCode(str: string): str is AttributeCode {
  return // some complex test
}
function checkItemId(str: string): str is ItemId {
  return // some other complex test
}

So I could do something like

function getAttribute(code: AttributeCode): AnAttributeObject {
  // do something with code, knowing before hand it's already been checked.
}

const someString = "hello";
if (checkAttributeCode(someString)) {
  getAttribute(someString);
}

but sadly typescript doesn't flag (below) as a problem

const someUncheckedString = "I am invalid mwahaha"
getAttribute(someUncheckedString);

Now, I know I can wrap the string in an object or class, and pass this object with the type "AttributeCode" around instead, but I am trying to avoid this and keeping it as a warded string instead, so any function that can accept a string can do so without having to be unwrapped

WORMSS
  • 1,625
  • 28
  • 36
  • 1
    Seems like a duplicate of https://stackoverflow.com/questions/49432350/how-to-represent-guid-in-typescript/49432424#49432424 – Titian Cernicova-Dragomir Mar 17 '22 at 16:12
  • Interesting. it appears they have called warded strings as branded string.. Okay, explains why I couldn't find it. Unioning string with a faked object allowing for infinite warded strings.. I like it.. I doubt my manager will like this, but it's worth a try.. Thank you @TitianCernicova-Dragomir – WORMSS Mar 17 '22 at 19:47

0 Answers0