Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow operators and indexing with intersections involving primtive types #6947

Merged
merged 4 commits into from
Feb 9, 2016

Conversation

ahejlsberg
Copy link
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
Member

👍

1 similar comment
@mhegazy
Copy link
Contributor

mhegazy commented Feb 8, 2016

👍

@DanielRosenwasser
Copy link
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
Copy link
Contributor

Arnavion commented Jun 17, 2016

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