Typescript接口,类型对象

时间:2017-12-13 12:40:23

标签: typescript

{
  title: 'my title',
  subtitle: 'my subtitle',
  description: 'my description',
  link: {
    title: 'my link title',
    uri: 'my link uri'
  }
}

我想使用界面格式化。我试过这样的程序没有成功:

export interface BlockRight {
  title: string;
  subtitle: string;
  description: string;
  link: Link;
}

interface Link {
  title: string;
  uri: string;
}

link似乎无效。如何为这个json结构创建一个接口?感谢。

2 个答案:

答案 0 :(得分:0)

在分配任何内容之前,您应首先实例化您的链接属性:

interface Link {
 title: string;
 uri: string;
}

interface BlockRight {
  title: string;
  subtitle: string;
  description: string;
  link: Link;
}

let block: BlockRight = {} as BlockRight;

block.title = 'title';
block.subtitle = "subtitle";
block.description = 'description';
block.link = {} as Link;
block.link.title = 'google';
block.link.uri = 'https://google.com';
console.log(block);

答案 1 :(得分:0)

你可以这样做。应该声明可选属性?跟随他们就像我在下面的例子中声明了描述。

export interface BlockRight {
title: string;
subtitle: string;
description?: string;
link: Link;
}
interface Link {
title: string;
uri: string;
}

let blockRight:BlockRight = {title:"MyTitle", subtitle:"My Subtitle", description: "MyDescription", link: {title: "My Link Title", uri:"mypath"}};