Typescript:此接口的正确语法是什么?

时间:2019-11-22 15:12:24

标签: typescript interface

我正在关注文档,但似乎我的语法与界面示例不符。我正在http://www.typescriptlang.org/play/?ssl=5&ssc=9&pln=5&pc=23#code/FDCWDsBcFMCcDMCGBjaACA8gIwFZoN7BrEFEnnjQDOMAJgAqwD2ADnJAJ4BcaNsEAczLEAvsDHBkTcDTRNcPbHgC8BNJRrQGzNrE48A5BroA1RABsArtANoJUmU3PQAdOaYCAFPJwvjWxlZ2DgBKAG4QSWlZHwAmHnx1ajpA3U543kh+cAE7NFVE-20gvQ4MgwA3C2tY23top1d3Lzi-ZICdYNjwoA

的操场上测试此代码
// Example 1. 
// has a red lint on myProperty: "Unused label." 
// also a red lint on string: "string is a type but being used as a value"
interface Obj {
    {
        myProperty: string
    }
}
const obj: Obj = { myProperty: 'value' }
console.log(obj.myProperty); // console error: string is not defined


// Example 2: Works as expected
const obj2: { myProperty2: string } = { myProperty2: 'value2' }
console.log(obj2.myProperty2);

在上面的界面中定义的单个属性对象的正确语法是什么?

更新1

这是我正在使用的API的示例POST响应,我很好奇编写对此模型进行建模的接口的最佳方法是:

HTTP/1.1 201 Created
{
  "script_tag": {
    "id": 870402694,
    "src": "https://djavaskripped.org/fancy.js",
    "event": "onload",
    "created_at": "2019-10-16T16:14:18-04:00",
    "updated_at": "2019-10-16T16:14:18-04:00",
    "display_scope": "all"
  }
}

1 个答案:

答案 0 :(得分:1)

您也应该这样命名容器属性

interface Obj {
  containerProperty: {
    nestedProperty: string;
  }
}

或者,如果您不想嵌套,则可以像这样定义接口

interface Obj {
  myProperty: string;
}