理解接口

huangapple go评论51阅读模式
英文:

Understand interfaces

问题

我不理解这段代码:

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

我明白全局方式的类型在我们应用程序的业务对象中通用化使用,类型允许捕获用户在函数中提供的类型。

但是在上面的代码中,我不明白:

  • 方括号语法在属性中的用处;
  • 接口具有属性,其值是接口本身的事实。接口是否可以递归?
英文:

I don't understand this code:

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

I understand that types in a global way serve a function to generalize its use with the business objects of our applications. Types allow to capture the type the user provides in the function.

But in the above code I don't understand:

  • the usefulness of the syntax with brackets for the property;
  • the fact that the interface has a property whose value is the interface itself. Are interfaces recursive?

答案1

得分: 1

以下是您要翻译的代码部分:

It is typescript not angular first

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

And I think this is better use key

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

in your example [] is used for key that can be string only. It can't be

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

Key should be string only like

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

回答部分已经翻译为中文并包含在您的请求中。

英文:

It is typescript not angular first

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

And I think this is better use key

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

in your example [] is used for key that can be string only. It can't be

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

Key should be string only like

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

Answer The fact that the interface has a property whose value is the interface itself. Are the interfaces recursives

Yes they are

答案2

得分: 1

The [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,
}

Playground

英文:

The [propertyName:string] means this interface can have zero or multiple keys, like a map. Why the value could be again the same data type could be if you want to represent some child items or binary trees. Here is a example how this interface could be used:

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

Playground

huangapple
  • 本文由 发表于 2023年5月7日 22:51:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194638.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定