Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从接口克隆具有密钥的对象_Javascript_Typescript - Fatal编程技术网

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
};