[TypeScript] Make Properties and Index Signatures Readonly in TypeScript

TypeScript 2.0 introduced the readonly modifier which can be added to a property or index signature declaration. It helps prevent against unintended property assignments. This lesson gives various use cases for readonly and shows what the generated JavaScript code looks like.

 

Normal use case for 'readonly':

interface User {
   readonly id: nunber;  
   name: string
} 

class User {

  readonly id: number;
   name: string; 
  constructor(
      id: number, name: string
  ) {
      this.id = id;
      this.name = name;
  }
}

 

Make a array readonly:

const level: ReadonlyArray<string> = [
 'master',
 'beginner'
];

 

posted @ 2017-11-09 21:06  Zhentiw  阅读(273)  评论(0编辑  收藏  举报