我试图在我在Typescript中定义的NodeJ中创建和使用一些数据类,而这正是我想知道是否有更简单的方法。
在javascript中我能够做到
let myBuilding = new Building
那我就可以做
myBuilding.col1 = "Wall"
myBuilding.col2 = "None"
以此类推
在打字稿中,如果我没有在声明时声明所有内容,它就不会喜欢它。有没有办法用空值初始化一个类,然后再分配它们呢?当某些东西没有赋值时,也会发生什么呢?在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;
}
}
答案 0 :(得分:0)
以下是实现此目的的四种方法:
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
,而无需创建用于强制类型的包装器。他们都有很多避开/忘记类型系统的方法。
设置方法和直接公共领域分配是最简单的类型安全方式。
这是一种无需先初始化即可一次性设置多项功能的方法
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"
});
答案 1 :(得分:0)
当您声明类型时,您可以将其设置为可选:
class Building {
height?: number;
}
如果您不立即声明高度,但是现在打字稿将不会抱怨,但是您仍然无法添加额外的未声明字段,例如宽度。
如果它们满足接口的某些子集,但不是所有必填字段,则也可以将其声明为Partial<Building>
。