Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i add a readonly attribute to a declarations file?

Tags:

typescript

I'm creating a declarationsfile for a library that doesnt exist yet, but there are some classes in there that have readonly attributes. How can i put that in the declaration?

like image 462
Eindbaas Avatar asked Feb 10 '13 10:02

Eindbaas


People also ask

How do you add a Read Only attribute?

Use setAttribute() Method to add the readonly attribute to the form input field using JavaScript. setAttribute() Method: This method adds the defined attribute to an element, and gives it the defined value. If the specified attribute already present, then the value is being set or changed.

How do you set a readonly property in HTML?

The Boolean readonly attribute, when present, makes the element not mutable, meaning the user can not edit the control. If the readonly attribute is specified on an input element, because the user can not edit the input, the element does not participate in constraint validation.

How do I make a read only field editable in JavaScript?

A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it. Tip: To prevent the user from interacting with the field, use the disabled property instead.

How do I set the Read Only attribute in jQuery?

Projects In JavaScript & JQuery To make a textarea and input type read only, use the attr() method .


2 Answers

Strangely, you can't specify getters and setters on interfaces or on ambient declarations.

The closest you can get is:

interface Test {
    Prop: number;
}

class Example implements Test {
    private prop: number;

    get Prop() :number {
        return this.prop;
    }
}

Unfortunately, this doesn't prevent the implementation from allowing a setter and in the context of an ambient declaration it wouldn't prevent the caller from attempting to set the value.

like image 195
Fenton Avatar answered Oct 08 '22 20:10

Fenton


With TypeScript 2.0 you can now declare readonly properties, for example

interface Point {
    readonly x: number;
    readonly y: number;
}

var p1: Point = { x: 10, y: 20 };
p1.x = 5;                            // Error, p1.x is read-only

var p2 = { x: 1, y: 1 };
var p3: Point = p2;                  // Ok, read-only alias for p2
p3.x = 5;                            // Error, p3.x is read-only
p2.x = 5;                            // Ok, but also changes p3.x because of aliasing

see here for more details.

like image 41
Burt_Harris Avatar answered Oct 08 '22 19:10

Burt_Harris