Javascript 如何从接口克隆具有密钥的对象
假设我有一个对象和接口Javascript 如何从接口克隆具有密钥的对象,javascript,typescript,Javascript,Typescript,假设我有一个对象和接口 type A { one: string, two: number, three: string | undefined } const a: A = { one: 'test', two: 1, three: 'test'}; type B { one: string, three: number, four: number } 我想创建一个名为B的对象,该对象将从A克隆,但具有公用键和具有相同类型 所以我想要一个函数,当我输入object
type A {
one: string,
two: number,
three: string | undefined
}
const a: A = { one: 'test', two: 1, three: 'test'};
type B {
one: string,
three: number,
four: number
}
我想创建一个名为B
的对象,该对象将从A
克隆,但具有公用键和具有相同类型
所以我想要一个函数,当我输入objectA和typeB时,它将帮助我返回B={one:'test'}
谢谢您可以使用标准解决方案,如下所示
const b=JSON.parse(JSON.stringify(a))
或
这将克隆对象a,并且在分配后不会将对象a的任何引用包含到对象b
如果要使用本机typescript解决方案,可以使用从
a
到B
type A = {
one: string;
two: number;
three: string | undefined;
};
type B = Pick<A, "one">;
const b: B = {
one: 'test'
};
const b2: B = {
one: 'test'
two: 'test'; // u'll get a warning
};
A型={
一:弦,;
二是数量;
三:字符串|未定义;
};
B类=拾取;
常数b:b={
一:"测试"
};
常数b2:B={
一:"测试"
二:“测试”;//你会得到警告
};
您是否尝试过此方法:lodash是一个很好的对象操作库const B=({one}=a)
@bharattatel谢谢您的建议,这看起来很棒,但我也在寻找一个原生的typescript解决方案将您的类型定义为类,在复制过程中您可以迭代prototype@StackSlave这只在我知道“一”键的情况下起作用。我想有一个更一般的解决方案嗨,这需要我知道'one'关键字,我实际上在寻找一个函数来帮助我创建对象
type A = {
one: string;
two: number;
three: string | undefined;
};
type B = Pick<A, "one">;
const b: B = {
one: 'test'
};
const b2: B = {
one: 'test'
two: 'test'; // u'll get a warning
};