Angular 中的只读预设值

huangapple go评论88阅读模式
英文:

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

  1. public class Dto {
  2. private id: number;
  3. private desc: string;
  4. constructor(desc: string){
  5. this.desc = desc;
  6. this.id = Generator.getRandomId();
  7. }
  8. // Getter for both
  9. // Setter for desc
  10. }

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

  1. public class Dto {
  2. private long id;
  3. private String desc;
  4. public Dto(String desc){
  5. this.desc = desc;
  6. id= Generator.getRandomId();
  7. }
  8. //Getter for both
  9. // Setter for desc
  10. }

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中几乎是相同的:

  1. class Dto {
  2. private readonly id: number;
  3. private desc: string;
  4. constructor(desc: string) {
  5. this.desc = desc;
  6. this.id = Generator.getRandomId();
  7. }
  8. }

或者使用接口:

  1. interface Foo {
  2. readonly id: string;
  3. desc: string;
  4. }
  5. declare const foo: Foo;
  6. foo.id = ''; // 错误
英文:

It's pretty much the same in TS :

  1. class Dto {
  2. private readonly id: number;
  3. private desc: string;
  4. public Dto(desc: string) {
  5. this.desc = desc;
  6. this.id = Generator.getRandomId();
  7. }
  8. }

or with an interface :

  1. interface Foo {
  2. readonly id: string;
  3. desc: string;
  4. }
  5. declare const foo: Foo;
  6. foo.id = '' // Error

huangapple
  • 本文由 发表于 2023年2月27日 19:00:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75579608.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定