0

If I create a custom type such as:

type LowercaseString = string

And then use it in a function like this:

function displayLowercaseString(input: LowercaseString) {
  ...
}

displayLowercaseString('UPPERCASE')

The above example compiles perfectly and runs, since 'UPPERCASE' is of type string and so is LowercaseString

My question is, is it possible to have a TS error such as type string does not match LowercaseString so that I am forced to put every string through a function like this before using it in displayLowercaseString:

function stringToLowercase(input: string): LowercaseString {
  return input.toLowercase as LowercaseString
}
2
  • 1
    What you're looking for is essentially github.com/microsoft/TypeScript/issues/41160, which has been open for years and is not likely to be resolved anytime soon. Commented Jul 10, 2022 at 14:18
  • By using a string in my example I think I have created a misleading question. I don't want any kind of validation of the content of the strings. I effectively just want type names to be matched. type ID = number is another example, where I wouldn't want a function that accepts type ID to just accept any number. It should only accept variables with the type ID Commented Jul 10, 2022 at 15:16

1 Answer 1

1

You can use a branded type :

type LowercaseString = string & { __brand: 'lower' };


function stringToLowercase(input: string): LowercaseString {
  return input.toLowerCase() as LowercaseString
}

function displayLowercaseString(input: LowercaseString) {
}

const uppercaseString = 'UPPERCASE';
displayLowercaseString(uppercaseString) // nope 
displayLowercaseString(stringToLowercase(uppercaseString)) // ok

Playground

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, this is exactly what I was looking for and works perfectly! Am I correct in assuming that this does not add any additional code when compiled to JavaScript? (as with normal TS types)
@StanFlint Yes, this is purely typechecking code. You can look at the generated code in the playground !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.