打字稿中的只读变量与只读类型方法
Readonly variable vs Readonly-Typed method in typescript
打字稿中只读变量和只读类型方法有什么区别?
只读变量
length: Readonly<Number | number | String | string> = 1;
对
只读类型方法
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<T>
is an object-type mapping:
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
它将使 T
的所有属性对编译器显示为只读 - 因此在 number
或 string
上使用它实际上没有意义开始与,因为两者都没有属性。
如果你想要一个真正的只读——但内部可更改——属性 在 运行-时间然后使用 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;
}
}
Readonly<T>
类型的变量和 returns 类型 Readonly<T>
变量的方法没有区别,只是使用方法的额外步骤。
打字稿中只读变量和只读类型方法有什么区别?
只读变量
length: Readonly<Number | number | String | string> = 1;
对
只读类型方法
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<T>
is an object-type mapping:
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
它将使 T
的所有属性对编译器显示为只读 - 因此在 number
或 string
上使用它实际上没有意义开始与,因为两者都没有属性。
如果你想要一个真正的只读——但内部可更改——属性 在 运行-时间然后使用 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;
}
}
Readonly<T>
类型的变量和 returns 类型 Readonly<T>
变量的方法没有区别,只是使用方法的额外步骤。