英文:
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,
}
英文:
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,
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论