使用构造函数分配的不同行为的键
Keyof different behavior using constructor assignment
我遇到了 "keyof" 使用构造函数赋值的不同行为...
class Class1 {
constructor(private a: number, private b: string) {
}
method1() {
console.log("method1");
}
}
class Class2 {
a: number;
b: string;
constructor() {
}
method1() {
console.log("method1");
}
}
type Cet1Props = keyof Class1; // "method1"
type Class2Props = keyof Class2; // "a" | "b" | "method1"
我不明白为什么会这样,有人能解释一下吗?
谢谢!!
在 Class2
中它们是 public(这是默认值),而在 Class1
中它们是私有的。
为了使它们具有可比性(即证明它与构造函数赋值无关)将私有访问修饰符添加到 Class2
(或更改 Class1
使它们成为 public
).
class Class2 {
private a: number;
private b: string;
constructor() {
}
method1() {
console.log("method1");
}
}
如果 a
和 b
成员是私有的,您将得到:
type Class2Props = keyof Class2; // "method1"
我遇到了 "keyof" 使用构造函数赋值的不同行为...
class Class1 {
constructor(private a: number, private b: string) {
}
method1() {
console.log("method1");
}
}
class Class2 {
a: number;
b: string;
constructor() {
}
method1() {
console.log("method1");
}
}
type Cet1Props = keyof Class1; // "method1"
type Class2Props = keyof Class2; // "a" | "b" | "method1"
我不明白为什么会这样,有人能解释一下吗?
谢谢!!
在 Class2
中它们是 public(这是默认值),而在 Class1
中它们是私有的。
为了使它们具有可比性(即证明它与构造函数赋值无关)将私有访问修饰符添加到 Class2
(或更改 Class1
使它们成为 public
).
class Class2 {
private a: number;
private b: string;
constructor() {
}
method1() {
console.log("method1");
}
}
如果 a
和 b
成员是私有的,您将得到:
type Class2Props = keyof Class2; // "method1"