了解界面

问题描述 投票:0回答:2

Angular 的新手,我不明白这段代码:

export interface MyType {
  [propertyName: string]: string | MyType;
}

我理解全局类型的作用是将其与我们应用程序的业务对象一起使用。类型允许捕获用户在函数中提供的类型。

但是上面的代码我看不懂:

  • 带括号的语法对属性的用处
  • 接口有一个属性,其值为接口本身。接口是递归的吗?

感谢帮助

angular typescript interface
2个回答
0
投票

先是typescript不是angular

export interface MyType {
  [propertyName: string]: string | MyType;
}

我认为最好使用 key

interface MyType {
  [key: string]: string | MyType;
}

在你的例子中 [] 用于只能是字符串的键。不可能

let x : MyType = {1:"sss"}

Key 应该只是字符串,如

let x : MyType = {"1":"sss"}

0
投票

[propertyName:string]
表示这个界面可以有零个或多个键,就像地图一样。如果你想表示一些子项或二叉树,为什么值可能再次是相同的数据类型。这是一个如何使用此接口的示例:

interface MyType {
  [propertyName: string]: string | MyType;
}

const a : MyType = {foo: 'bar'}
const b : MyType = {key1: a, key2: 'bar', key3: 'three'}
const c : MyType = {a, b}

const bar: MyType = {
    a,
    b,
    c,
}

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.