英文:
Readonly preseted values in Angular
问题
I'm new to Angular and TypeScript and in the process of mastering those, I run upon a task where I need an object (or something alike) which gives me the opportunity to define an attribute which is readable but not editable.
In Java I would have done it like this
public class Dto {
private id: number;
private desc: string;
constructor(desc: string){
this.desc = desc;
this.id = Generator.getRandomId();
}
// Getter for both
// Setter for desc
}
Is there any way to do something similar in TypeScript?
I was told to do this with an Interface but by this time, I'm quite overasked.
Thanks!
英文:
I'm new to Angular and TypeScript and in the process of mastering those, I run upon a task where I need an object (or something alike) which gives me the opportunity to define an attribute which is readable but not editable.
In Java I would have done it like this
public class Dto {
private long id;
private String desc;
public Dto(String desc){
this.desc = desc;
id= Generator.getRandomId();
}
//Getter for both
// Setter for desc
}
Is there any way to do something similar in TypeScript?
I was told to do this with an Interface but by this time, I'm quite overasked.
Thanks!
答案1
得分: 1
在TypeScript中几乎是相同的:
class Dto {
private readonly id: number;
private desc: string;
constructor(desc: string) {
this.desc = desc;
this.id = Generator.getRandomId();
}
}
或者使用接口:
interface Foo {
readonly id: string;
desc: string;
}
declare const foo: Foo;
foo.id = ''; // 错误
英文:
It's pretty much the same in TS :
class Dto {
private readonly id: number;
private desc: string;
public Dto(desc: string) {
this.desc = desc;
this.id = Generator.getRandomId();
}
}
or with an interface :
interface Foo {
readonly id: string;
desc: string;
}
declare const foo: Foo;
foo.id = '' // Error
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论