typescript - 在跳过字段的同时构造一个对象
问题描述
打字稿新手。我正在尝试用任意形状的另一个对象构造一个对象:
class Thing {
a?: string;
b?: string;
}
const input = {a: 'a', b: 'b', c: 'c'}
const builtInput: Thing = {
...input
}
console.log(builtInput)
我期待
{a: "a", b: "b"}
但得到
{a: "a", b: "b", c: "c"}
我也尝试过thing
作为类型和接口。没有任何效果。我是否期待太多魔法并需要编写自定义构造函数?有打字稿的方法吗?
解决方案
您应该编写一个函数,该函数将创建一个带有所需键的对象。我认为,这样的事情会很有用:
// initial type
type Input = {
a: string;
b: string;
c: string;
}
// result type
type Build = Pick<Input, 'a' | 'b'>;
const getFilteredInput = <T extends {}, K extends keyof T>(obj: T, requiredVals: Array<K>) => {
return requiredVals.reduce((acc, current) => {
if (current in obj) {
acc[current] = obj[current];
}
return acc;
}, {} as Pick<T, K>);
// Pick describes an object from T with only K keys
};
const input: Input = {
a: 'a',
b: 'b',
c: 'c',
};
const build: Build = getFilteredInput(input, ['a', 'b']);
console.log('build', build);
推荐阅读
- javascript - JavaScript 更改了不正确的元素并且没有应用于所需的元素
- python - 为什么python不允许从不同的目录写入文件?
- javascript - 返回回调或承诺的函数
- python - 使用 Telebot 库更改 Telegram Group 的描述
- javascript - 从父窗口跨域调用子 iFrame JS 函数
- r - 如何根据 R 中其他两列的值组合更改列值?
- html - 如何在使用引导程序 4 工具提示时禁用默认的 html-5 工具提示
- php - 使用 PHP cURL POST JSON 数据
- python - 在 Django 中添加对谁可以编辑帖子的用户限制
- javascript - 使用正则表达式 Javascript 查找子字符串