简体   繁体   English

打字稿中的只读变量vs只读类型方法

[英]Readonly variable vs Readonly-Typed method in typescript

What is the difference between Readonly variable and Readonly-Typed Method in typescript? Typescript中的Readonly变量和Readonly-Typed方法有什么区别?

Readonly Variable 只读变量

length: Readonly<Number | number | String | string> = 1;

vs VS

Readonly-typed Method 只读类型的方法

length(lenght: Number | number | String | string): Readonly<Number | number | String | string> {
        var width: Readonly<Number | number | String | string> = lenght;
        return width;
    }
  • What are the difference's for those thinks? 这些想法有什么不同?
  • And is it possible to assign value for Readonly function on runtime? 是否可以在运行时为Readonly函数分配值?

Readonly<T> is an object-type mapping : Readonly<T> 是一个对象类型映射

type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};

It will make all properties of T appear read-only to the compiler - So it doesn't actually make sense to use it on either number or string to begin with, because neither have properties. 它会使T所有属性对编译器都是只读的-因此,以T开头的任何numberstring实际上都没有意义,因为它们都不具有属性。

if you want a true read-only --but internally changeable-- property at run-time then use a getter. 如果您希望在运行时提供一个真正的只读(但内部可更改)属性,请使用getter。

interface IFoo {
  readonly length: number;
}

class Foo implements IFoo {
  private _length: number;

  get length(): number {
    return this._length;
  }

  change(length: number) {
    this._length = length;
  }
}

There is no difference between a variable typed Readonly<T> and a method that returns a variable typed Readonly<T> bar the extra step of using a method. 有类型的变量之间没有差别Readonly<T>和返回类型的变量的方法, Readonly<T>扎使用方法的额外的步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM