23

I just wonder - is it a way to check if the string matches some pattern via TypeScript.

I don't want to do the checks in the runtime.

//What I have now
public id: string; //can be whatever string 

//What I want to see
public id: IdType; //Some type?
id = '0000-0000-0000-0001'//valid
id = 'whatever'//invalid

So is it a way to define string format?

5
  • With regular expressions Commented Nov 8, 2017 at 10:11
  • I'm not sure if you can do it. Pattern is not a type. You can though add validator to check the value Commented Nov 8, 2017 at 10:20
  • @Rajesh But it will be a runtime check, right? I just interested to check it during compilation Commented Nov 8, 2017 at 10:23
  • 1
    @SergeiPanfilov Yes. That will be a runtime check. Think about this, how will TS know what the value is just by type? TS can check for type but the value is processed during runtime only. So unless value is actually set, you cannot check it Commented Nov 8, 2017 at 10:31
  • 2
    Not possible yet. There's only suggestion - exactly what you're looking for Commented Nov 8, 2017 at 11:58

1 Answer 1

37

This should now be possible as of TS 4.1 beta

There's now a feature called Template Literal Types, which looks something like this (excuse the basic example):

type idType = `${number}-${number}-${number}-${number}`
const id: idType = '0000-0000-0000-0001';

https://devblogs.microsoft.com/typescript/announcing-typescript-4-1-beta/#template-literal-types

Playground

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

4 Comments

This unfortunately won't work because template literal types allow only concrete literal types typescriptlang.org/play?ts=4.1.0-beta#code/…
Seems to be working in the nightly builds. Might just be on its way :)
This is now working in 4.1.5: typescriptlang.org/play?ts=4.1.5#code/…
How do you make this flexible? Maybe there's more '${number}' groups or fewer? working with paths here.

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.