1

I would like to make sure, that string contains other string, at transpile time:

type OneOrTwo = "one" | "two"
type StringContainingOneOrTwo = string
let str: StringContainingOneOrTwo = "123" + "one" // ok, contains OneOrTwo
let str2: StringContainingOneOrTwo = "123" + "onesss" // should fail, does not contain OneOrTwo
1
  • This is getting closer, with microsoft/TypeScript#40336, but the compiler still doesn't understand that the expression "123"+"one" has the type "123one"
    – jcalz
    Commented Sep 3, 2020 at 1:36

1 Answer 1

1

Typescript How to express string concatenation in type system

You can't do that. Especially with contains e.g. your example

let str2: StringContainingOneOrTwo = "123" + "onesss" // should fail, does not contain OneOrTwo

Actually does contain one i.e. 123 + one + sss. But even with ends with you can't encode that in the typescript type system.

2
  • 1
    Relevant GitHub issue: Microsoft/TypeScript#6579, suggestion to support regexp validated string literal types
    – jcalz
    Commented May 29, 2018 at 12:49
  • Regex validation would still (probably) not validate concatenation 'a'+'b'. Only 'ab'.
    – basarat
    Commented May 30, 2018 at 0:07

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.