Skip to content

Allow operators and indexing with intersections involving primtive types#6947

Merged
ahejlsberg merged 4 commits into
masterfrom
operatorsAndIntersections
Feb 9, 2016
Merged

Allow operators and indexing with intersections involving primtive types#6947
ahejlsberg merged 4 commits into
masterfrom
operatorsAndIntersections

Conversation

@ahejlsberg

Copy link
Copy Markdown
Member

Fixes #5599.

This PR allows operators and indexing to work with intersection types that include primitive types, making it easier to create and use "tagged" primitive types. For example:

type Guid = string & { $Guid };          // Tagged string type
type SerialNo = number & { $SerialNo };  // Tagged number type

function createGuid() {
    return "21EC2020-3AEA-4069-A2DD-08002B30309D" as Guid;
}

function createSerialNo() {
    return 12345 as SerialNo;
}

let map1: { [x: string]: number } = {};
let guid = createGuid();
map1[guid] = 123;  // Can index with tagged string

let map2: { [x: number]: string } = {};
let serialNo = createSerialNo();
map2[serialNo] = "hello";  // Can index with tagged number

// Operators treat tagged primitives as regular primitives
const s1 = "{" + guid + "}";
const s2 = guid.toLowerCase();
const s3 = guid + guid;
const s4 = guid + serialNo;
const s5 = serialNo.toPrecision(0);
const n1 = serialNo * 3;
const n2 = serialNo + serialNo;
const b1 = guid === "";
const b2 = guid === guid;
const b3 = serialNo === 0;
const b4 = serialNo === serialNo;

@RyanCavanaugh

Copy link
Copy Markdown
Member

👍

1 similar comment
@mhegazy

mhegazy commented Feb 8, 2016

Copy link
Copy Markdown
Contributor

👍

@DanielRosenwasser

Copy link
Copy Markdown
Member

What about someConstituentsHaveKind instead of maybeTypeOfKind?

ahejlsberg added a commit that referenced this pull request Feb 9, 2016
Allow operators and indexing with intersections involving primtive types
@ahejlsberg ahejlsberg merged commit 9dfaa30 into master Feb 9, 2016
@ahejlsberg ahejlsberg deleted the operatorsAndIntersections branch February 9, 2016 14:15
@Arnavion

Arnavion commented Jun 17, 2016

Copy link
Copy Markdown
Contributor

I wonder why Guid itself is not allowed to be in the signature still? That is, why does map1 still need to be indexed by a string key instead of Guid ?

Edit: The motivation would be to disallow indexing with anything that's not a Guid.

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants