gpt4 book ai didi

typescript - 分配 Typescript 构造函数参数

转载 作者:搜寻专家 更新时间:2023-10-30 20:36:52 25 4
gpt4 key购买 nike

我有接口(interface):

export interface IFieldValue {
name: string;
value: string;
}

我有一个实现它的类:

class Person implements IFieldValue{
name: string;
value: string;
constructor (name: string, value: string) {
this.name = name;
this.value = value;
}
}

看完this post我在考虑重构:

class Person implements IFieldValue{
constructor(public name: string, public value: string) {
}
}

问题:在头等舱中,我有默认情况下应为 private 的字段。在第二个示例中,我只能将它们设置为 public。我对 TypeScript 中默认访问修饰符的理解是否完全正确?

最佳答案

Public by default.TypeScript Documentation

定义如下

class Person implements IFieldValue{
name: string;
value: string;
constructor (name: string, value: string) {
this.name = name;
this.value = value;
}
}

属性 <Person>.name<Person>.value默认情况下是公开的。

因为他们在这里

class Person implements IFieldValue{
constructor(public name: string, public value: string) {
this.name = name;
this.value = value;
}
}

注意:这是一种不正确的做法,因为 this.namethis.value将被视为未在构造函数中定义。

class Person implements IFieldValue{
constructor(name: string, value: string) {
this.name = name;
this.value = value;
}
}

要使这些属性成为私有(private)属性,您需要将其重写为

class Person implements IFieldValue{
private name: string;
private value: string;
constructor (name: string, value: string) {
this.name = name;
this.value = value;
}
}

或等效

class Person implements IFieldValue{
constructor (private name: string, private value: string) {}
}

对于 TypeScript 2.X,由于接口(interface)具有公共(public)属性,您需要更改 privatepublic还有export

export class Person implements IFieldValue{
constructor (public name: string, public value: string) {}
}

在我看来,这是避免冗余的最佳方式。

关于typescript - 分配 Typescript 构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41923069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com