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