需要使用陣列中的值作為鍵來創建新物件。
并且需要實作tap完成。
const keys = ['name', 'age', 'contact', 'response'];
let obj = {};
keys.forEach(key => {
obj[key] = row[key];
});
obj. //need to know what are the properties previously added.
打字稿需要了解物件的名稱、年齡和聯系人屬性。
uj5u.com熱心網友回復:
// `as const` makes strings be string literals
const keys = ['name', 'age', 'contact', 'response'] as const;
// theese are the keys union ('name' | 'age' | ...)
type KeyType = typeof keys[number]
// row has data on what object will be
type RowType = typeof row
// the `obj` is the copy of `row` with only `keys` keys
type FullObjType = Pick<RowType, KeyType>
// the `obj` properties are not set yet
type ObjType = Partial<FullObjType>
let obj: ObjType = {};
for (let k of keys) {
obj[key] = row[key]
}
let fullObj: FullObjType = obj;
或者反過來,
function PickKeys<T, K extends keyof T>(row: T, keys: K[]) {
return Object.fromEntries(keys.map(k => [k, row[k]])) as Pick<T, K>
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/514944.html
標籤:打字稿目的类型
