1

Let me explain by example.

In a Field called Component you should be able to have these values> "M", "B", "A.

So you go ahead an define: type Component = "M" | "B" | "A";

So far so good. But it should be possible to also have a combination of these to assign like this: const MyComponent : Component = "MB"; or const MyComponent : Component = "BA";

How to define that?

pungggi
  • 1,263
  • 14
  • 25
  • 1
    hmm maybe this could a solution some time in the future https://github.com/microsoft/TypeScript/issues/6579 – pungggi Nov 10 '19 at 06:10

3 Answers3

2

Starting with TypeScript 4.1 this is possible with template literal types. E.g.:

type Component = "M" | "B" | "A";
type ComponentCombination = `${Component}${Component}`;

const comb: ComponentCombination = "MB";
daniel-sc
  • 1,139
  • 11
  • 23
1

This is not currently possible using TypeScript, but you can validate such a string using RegEx, the following thread gives an example of how to do that: How can I split a string into segments of n characters?

You can also use this regex:

let value = 'MBA';

// string length 1-3 and contains M,B,A combinations
let validatorRegEx = /^([M|B|A]{1,3}$)/i; 
if(validatorRegEx.test(value)) {
    // code ...
}
Mor Shemesh
  • 2,689
  • 1
  • 24
  • 36
1

Simply find an interface for your data - it looks like you have a simple small set of values as a domain data for Component property. So maybe you should just extend your type (union):

type Component = "M" | "B" | "A" | "MA"

What do you think about introducing enum (string)?

enum Direction {
    A: "A",
    B: "B",
    M: "M",
    AB: "AB",
    // more values
}

At the end - don't think about data type as validator. So maybe in your case you should just use simple type "string" and validate it on demand or at initialization time.

John Smith
  • 1,091
  • 9
  • 17