Rytis Alekna
Rytis Alekna

Reputation: 1377

Intersection of two string types

I wanted to define a type by using generics that would declare concatenated string from two string types. I want to allow key to accept only a string "onetwo". Is that possible?

In my try below I get a compiler error that 'string' is not assignable to type Some and 'string' is not assignable to type "one"

type One = "one";
type Two = "two";
type Some = One & Two;

let key: Some = "one" + "two";

// my goal is this
function concat<A extends string, B extends string>(first: A, second: B): A & B { 
  return a+b; 
}

Upvotes: 1

Views: 86

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250036

Intersection types represent a type that is simultaneously both member types. In your case the concatenation of two strings is actually a new string literal type.

Typescript does not currently (as of version 3.2) have any way of representing such an operation on types

Upvotes: 2

Related Questions