我正在定義一個帶有由介面定義的建構式引數的 typescript 類,并且它將屬性限制為僅那些定義的屬性。
下面的代碼片段按預期作業,但是,有沒有辦法減少代碼以使其不那么重復?每個屬性被提及4次,一定有更好的方法。
interface MyInterface {
property1: string;
property2: boolean;
property3: number;
}
class MyClass {
property1: string;
property2: boolean;
property3: number;
constructor(parameters: MyInterface) {
this.property1 = parameters.property1;
this.property2 = parameters.property2;
this.property3 = parameters.property3;
}
}
const example = new MyClass({property1: "Property 1", property2: true, property3: 3, extraProperty: "Shouldn't exist"});
console.log(example);
編輯:我還需要在運行時限制具有其他未知屬性的物件的屬性。
uj5u.com熱心網友回復:
這個怎么樣?
interface MyInterface {
property1: string;
property2: boolean;
property3: number;
}
class MyClass implements MyInterface {
property1: string;
property2: boolean;
property3: number;
constructor(parameters: MyInterface) {
Object.assign(this, parameters);
}
}
uj5u.com熱心網友回復:
我相信這將是最簡潔的方式,但不一定是最好的。這取決于您的用例——特別是parameters建構式中的 是否總是與您的類的宣告屬性匹配。如果沒有,那么你會想堅持使用介面(無論如何使用介面可能更干凈)。
class MyClass {
property1!: string
property2!: boolean
property3!: number
constructor(parameters: typeof MyClass.prototype) {
Object.assign(this, parameters)
}
}
uj5u.com熱心網友回復:
interface MyInterface {
property1: string;
property2: boolean;
property3: number;
}
class MyClass implements MyInterface {
constructor(
public property1: string,
public property2: boolean,
public property3: number
) { }
}
const example = new MyClass("Property 1", true, 3, "Shouldn't exist");
console.log(example);
通過放入public建構式引數,我不需要在建構式之外宣告它們。MyClass實作MyInterface以便我知道我已經在MyClass.
也許這并不真正適用于您的需求,因為您必須在建構式中手動分配每個屬性,但它可能會給您一些思考。
uj5u.com熱心網友回復:
是的,這是可能的,但是您需要在parameters屬性中講述類引數:
interface MyInterface {
property1: string;
property2: boolean;
property3: number;
}
class MyClass {
constructor(public parameters: MyInterface) { }
}
const example = new MyClass({ property1: "Property 1", property2: true, property3: 3, extraProperty: "Shouldn't exist" });
console.log(example);
example.parameters.property1 // ok

如果你想在運行時驗證你的物件,你應該使用user-defined-type-guards或io-ts
TypeScript 具有靜態型別系統
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/334153.html
