Get/set accessors in interfaces

Topics: Language Specification
Oct 14, 2012 at 12:51 PM

Title pretty much says it. We don't have them and it would be a nice addition.

Oct 15, 2012 at 2:43 PM

I would expect an interface to define the property, but not whether it is implemented with getters and setters.

You can use getters and setters in TypeScript if you target ECMAScript 5, rather than the default ECMAScript 3 - but you should check browser support.

Coordinator
Oct 15, 2012 at 4:02 PM

Right, that's the idea.  An interface doesn't enforce a style of implementation, but rather says an API must exposed.  You can use interfaces to describe that a property should be available, and it's up to the implementer to decide how.

interface Foo {
	x:number;
}

class FooGetSet implements Foo {
	constructor(private my_x:number) { 
	}
	
	get x() { this.my_x = this.my_x + 1; return this.my_x; }
	
	public set x(new_x: number) { 
		this.my_x = 1000;
	}
}

class FooDirect implements Foo {
	constructor(public x:number) { }
}

var fgs = new FooGetSet(1);
var fd = new FooDirect(2);
Oct 15, 2012 at 4:09 PM

Maybe the request is really for the ability to describe read-only properties in an interface?

I agree that adding features to interfaces that would constrain the implementation is not desirable, which is why I wonder whether that's really what's being requested.

Oct 15, 2012 at 5:50 PM

Thanks, Alexjs. Read-only properties are exactly what I'm hoping for.

Coordinator
Oct 15, 2012 at 8:33 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.
Coordinator
Oct 15, 2012 at 8:33 PM

Ah yes, my bad.  That would be handy.  I've added this as a feature request.