8000 Contextual type assertion operator · Issue #2876 · microsoft/TypeScript · GitHub
[go: up one dir, main page]

Skip to content
Contextual type assertion operator #2876
Closed
@RyanCavanaugh

Description

@RyanCavanaugh

A contextual type assertion expression, <?>, is like a regular type assertion (e.g. <string>), but asserts to the contextual type of the expression.

About half of all type assertions can be rewritten this way with no loss of type safety.

Example:

declare function setDivText(div: HTMLDivElement): void;

// Error
setDivText(document.getElementById('myDiv'));
// OK, but a lot of typing

596F
setDivText(<HTMLDivElement>document.getElementById('myDiv'));
// OK and easy
setDivText(<?>document.getElementById('myDiv'));

It is an error to use a contextual assertion when no contextual type exists:

<?>foo; // Error
var x: number = <?>foo; // OK

This should nearly eliminate assertions to <any> due to people not wanting to type out large type literals.

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

      0