Angular 中的只读预设值

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

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

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:

确定