所以我想創建一個函式,它接受一個類并為它創建一個原型。但是在這個原型中,類的每個屬性都被定義了(包括可選的)。所以這就是我想要的:
class Bar {
public i?: number
//...
}
class Foo {
public a?: string;
public b?: number;
public c?: Array<string>;
public l?: boolean;
public d?: Bar;
//...
}
const prot = getPrototype<Foo>();
console.log(prot); //My expected output: { a: "", b: 0, c: [], l: false, d: {}, ... }
const prot2 = getPrototype<Bar>();
console.log(prot2); // My expected output: {i: 0, ...}
我真的看不出有什么辦法。如果你認為有辦法,我很樂意看到一個。賦予屬性的值應該是每種型別的硬編碼值。像這樣的東西:
//...
//... the logic for the getPrototype function ...
//...
if(typeof property === "string"){ prototype[property] = ""; }
else if(typeof property === "number"){ prototype[property] = 0; }
//...
//...
uj5u.com熱心網友回復:
我們可以通過使用映射型別和條件屬性來實作這一點,方法是創建一個型別別名InitializeType<T>并使用它來定義型別getPrototype<T>
class Bar {
public i?: number
//...
}
class Foo {
public a?: string;
public b?: number;
public c?: Array<string>;
public l?: boolean;
public d?: Bar;
//...
}
type InitializeType<T> = {} & {
[K in keyof T]-?:
string extends T[K]
? ""
: number extends T[K]
? 0
: boolean extends T[K]
? false
: Array<any> extends T[K]
? []
: object extends T[K]
? {}
: T[K]
}
declare function getPrototype<T>(): InitializeType<T>
const prot = getPrototype<Foo>();
console.log(prot); // output: { a: "", b: 0, c: [], l: false, d: {}, ... }
const prot2 = getPrototype<Bar>();
console.log(prot2); // output: {i: 0, ...}
代碼游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/468675.html
