我正在尝试在NodeJs中创建和使用一些数据类,这些类是我在Typescript中定义的,我想知道是否有更简单的方法。
在javascript中,我可以做到
let myBuilding = new Building然后我就能做
myBuilding.col1 = "Wall"
myBuilding.col2 = "None"诸若此类
在typescript中,如果我不在声明点声明所有内容,它就不会喜欢它。有没有一种方法可以用空值初始化一个类,然后在以后分配它们?还有,当有一些东西没有被赋值时会发生什么?在javascript中,我们不会得到返回项,这在从json解析到类时非常好
下面是我的一个类的样子
export class Exterior {
public exterior: string;
public fencing: string;
public security: string;
public sewer: string;
public lot: string;
public pool: string;
public patioPorch: string;
public spa: string;
constructor(exterior: string, fencing: string, security: string, sewer: string, lot: string, pool: string,
patioPorch: string, spa: string) {
this.exterior = exterior;
this.fencing = fencing;
this.security = security;
this.sewer = sewer;
this.lot = lot;
this.pool = pool;
this.patioPorch = patioPorch;
this.spa = spa;
}
}发布于 2019-04-03 10:01:20
以下是实现这一目标的四种方法:
class Foo {
// This will not do anything, so remove it
constructor() {}
// this will be undefined initially
private internalA!: number;
public get fieldA() {
return this.internalA
}
public set fieldA(internalAValue: number) {
this.internalA = internalAValue;
}
// this will be undefined initially
public fieldB!: boolean;
// this will be undefined initially
public fieldC!: string;
// this will be "example-initial-value" initially
public fieldD: string = "example-initial-value";
}
const foo = new Foo();
// Method 1 using setters
foo.fieldA = 2;
alert(foo.fieldA);
// Method 2 using simple assigning
foo.fieldB = true;
alert(foo.fieldB);
// Method 3 using Object.defineProperty
Object.defineProperty(foo, 'fieldC', {
value: "test",
writable: false
});
alert(foo.fieldC);
// Method 4 using Object.assign
Object.assign(foo, {fieldD: "hello"});
alert(foo.fieldD);要非常小心,甚至避免直接使用Object.defineProperty和Object.assign,而无需创建强制执行这些类型的包装器。它们都有很多绕过/忘记你的类型系统的方法。
setter方法和直接公共字段赋值是最简单的类型安全方法。
这里的是一种无需初始化第一个就可以一次设置多项内容的方法
interface IFooParams {
fieldA: number;
fieldB: boolean;
fieldC: string;
fieldD: string
}
class Foo {
// this will be undefined initially
public fieldA!: number;
// this will be undefined initially
public fieldB!: boolean;
// this will be undefined initially
public fieldC!: string;
// this will be "example-initial-value" initially
public fieldD: string = "example-initial-value";
public setAllInOneGo(params: IFooParams): void {
this.fieldA = params.fieldA;
this.fieldB = params.fieldB;
this.fieldC = params.fieldC;
this.fieldD = params.fieldD;
}
}
const foo = new Foo();
// Whenever:
foo.setAllInOneGo({
fieldA: 2,
fieldB: false,
fieldC: "hello",
fieldD: "world"
});发布于 2019-04-03 10:10:46
当您声明一个类型时,您可以将其设置为可选的:
class Building {
height?: number;
}现在,如果你不立即声明一个高度,typescript不会报错,但是你仍然不能添加额外的未声明的字段,比如width。
如果满足接口的某些子集,但不是所有必需字段,则还可以将其声明为Partial<Building>。
https://stackoverflow.com/questions/55484364
复制相似问题