xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Typescript & readonly property

Typescript & readonly property

https://www.typescriptlang.org/docs/handbook/classes.html#readonly-modifier

class Octopus {
    readonly name: string;
    readonly numberOfLegs: number = 8;
    constructor (theName: string) {
        this.name = theName;
    }
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // error! name is readonly.


https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlyt

interface Todo {
    title: string;
}

const todo: Readonly<Todo> = {
    title: 'Delete inactive users',
};

todo.title = 'Hello'; // Error: cannot reassign a readonly property

// Object.freeze

function freeze<T>(obj: T): Readonly<T>;

Object.freeze

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

const

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

refs

https://www.tutorialsteacher.com/typescript/typescript-readonly

class Employee {
    readonly empCode: number;
    empName: string;
    
    constructor(code: number, name: string)     {
        this.empCode = code;
        this.empName = name;
    }
}
let emp = new Employee(10, "John");
emp.empCode = 20; //Compiler Error
emp.empName = 'Bill'; //Compiler Error

https://mariusschulz.com/blog/read-only-properties-in-typescript



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-07-08 21:37  xgqfrms  阅读(301)  评论(1编辑  收藏  举报