[英]Convert TS interface keys to type values
我試圖在數據庫表 class 中有點花哨。 我希望用戶能夠只傳遞一個行接口(或 class,如有必要)並讓表 class 推斷如何創建表。
interface Row {
rowid: number
}
class Table<T extends Row> {
getRowDefinition(){
// magically use T to create col definitions
}
createTable(){
const defs = this.getRowDefinition();
const cols = defs.map(def => {
switch(def.type){
case 'string':
return `${def.name} TEXT`;
case 'number':
return `${def.name} INTEGER;
}
});
const sql = 'CREATE TABLE ...'; // use cols, etc
}
}
interface MyRow extends Row {
name: string
age: number
}
class MyTable extends Table<MyRow> {}
Typescript 類型在編譯時被刪除,因此它們在運行時不可用。
如果您創建一些類來確定每個行的類型,則可以使用instanceof
,並使用typeof
來確定運行時變量的類型。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.