Skip to content

TypeScript Object Initializer Syntax #16737

@MrMatthewLayton

Description

@MrMatthewLayton

Introduction

I would like to submit this proposal for discussion (and hopefully implementation into the language spec) to introduce object initializer syntax into TypeScript.

Rationale

TypeScript already gives us the ability to create record type classes through syntactic sugar that allows us to declare member variables that can be assigned via the constructor.

class Point {
    constructor(
        public x: number = 0,
        public y: number = 0) {
    }
}

This is really useful, and I find myself using this syntax more often than not, but there are cases where this syntax is not appropriate for an object; granted the example above essentially exposes a default constructor, since all parameters are optional, one could create a point with no arguments.

const point = new Point();

There are however cases where this is not appropriate; we may in some cases want to implement classes where member variables or properties are not set during constructor initialization. Point is actually not a great candidate for this but for argument sake...

class Point {
    public x: number = 0;
    public y: number = 0;

    constructor () {
    }
}

If we wanted to construct a point implemented like the one above, we would currently have to do so like this.

const point = new Point();
point.x = 123;
point.y = 456;

Solution

It would be nice if we had object initializer syntax which would make this a little easier.

const point = new Point() {
    x = 123;
    y = 456;
}

Which would compile to

const point = (function() {
    const point = new Point();
    point.x = 123;
    point.y = 456;
    return point;
})();

Before I Forget

I've read a few articles on alternative ways to do this with TypeScript, but frankly I don't like them, mainly because most of them only specify contractual constraints on object declarations and initialization, but require object literals to do so; my solution ensures that actually, you get back the expected type.

interface IPoint {
    x?: number;
    y?: number;
}

const point: IPoint = {
    x = 123;
}

This would compile, but it doesn't actually give you a Point instance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Out of ScopeThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions