Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.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
Typescript是否基于接口名称创建对象?_Typescript_Typescript2.0 - Fatal编程技术网

Typescript是否基于接口名称创建对象?

Typescript是否基于接口名称创建对象?,typescript,typescript2.0,Typescript,Typescript2.0,我有两个接口,我想创建一个与接口键相同的对象,我该怎么做 export interface First { first: string; } export interface Last { last: string; } export interface Gender { gender: boolean; } #I would like to have any result as following const obj = { first: 'first' last: 'la

我有两个接口,我想创建一个与接口键相同的对象,我该怎么做

export interface First {
  first: string;
}
export interface Last {
  last: string;
}
export interface Gender {
  gender: boolean;
}
#I would like to have any result as following
const obj = {
  first: 'first'
  last: 'last'
  gender: true,
}

您好,您需要添加变量类型接口

first: First;
last: Last;
gender:Gender;

export class AppComponent{
obj = {
  first: this.first,
  last: this.last,
  gender: this.gender,
}
}
我希望这对你有帮助 关于

您可以这样定义:


您正试图让一个类实现多个接口?当您说“结果”时,您的意思是您想要一个输出此对象的函数,还是只需要它的一个类型声明?既然我已经有了接口,我可以做些什么,使对象的键名与所有接口完全相同吗?因为如果我有超过40件物品,比如第一把钥匙。我不想将它们一一列出并赋值?@jacobcan118“完全像所有接口一样的键名”是什么意思?您认为编译器应该创建一组接口的交集,而不必提及这些接口吗?“我的代码中定义的所有接口”不是编译器可以理解的。也许你应该像
interface All{first:string,last:string,gender:boolean}
那样创建你的接口,然后参考
Pick
Pick
而不是声明
first
gender
等接口。
type Thing = First & Last & Gender

const obj: Thing = {
    first: 'a',
    last: 'b',
    gender: false
}