Skip to content

Allow intersected numbers to be used in arithmetics & element access #4372

@ivogabe

Description

@ivogabe

I was experimenting with intersection types and primitives, and I discovered that when you create an intersection type with a number, you can't use it in arithmetics and element access:

type extendedNumber = number & { extended: any };
let a: extendedNumber;
let obj: any;

a + 1; // Operator '+' cannot be applied to types 'number & { extended: any }' and 'number'.
obj[a]; // An index expression argument must be of type 'string', 'number', 'symbol, or 'any'.

Though you can't create properties on numbers, this can be useful to add brands to numbers, like this:

type int = number & { __intBrand: void };
function int(value: number) {
  return <int> (value | 0);
}

Currently intersections are only allowed on these locations if all parts of the intersection are number or string, but that rule should only apply to union types. Suggestion: for intersection types (at least) one type should be number (or string) if it's used in arithmetics or element access.

I've implemented a fix in #4373.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions