我能否以某种方式定义基于 TypeScript 中另一个接口的接口中的索引名称?
Can I somehow define what can be the indexed name in the interface based on another interface in TypeScript?
我有这个interface
:
export interface FieldContainerInterface {
[key: string]: FieldInterface;
}
我想根据其他接口定义 key
字符串。我希望使用这样的东西:
interface FieldContainerInterface<T> {
// in here how can I pick the fields from <T>?
[T<key>: string]: FieldInterface;
}
interface BanknoteInterface {
id: number;
deviza_id: number;
value: string;
}
class Banknote implements BanknoteInterface {
id: number;
deviza_id: number;
value: string;
fieldContainer: FieldContainerInterface<BanknoteInterface> {
// here I MUST to define id, defiza_id and value fields
}
我能以某种方式定义 FieldContainerInterface
中的 key
字符串吗?
不确定您要实现的目标,但将键限制为特定值的一种方法是使用 keyof
运算符。 Here 是一篇关于它的好文章。示例:
import React from 'react';
interface BanknoteInterface {
id: number;
deviza_id: number;
value: string;
}
type FieldContainerInterface<T> = {
[key in keyof T]?: any;
}
class Banknote implements BanknoteInterface {
id: number;
deviza_id: number;
value: string;
fieldContainer: FieldContainerInterface<BanknoteInterface> = {
// optionally add any key
value: "hello",
// id: 5,
// deviza_id: 5
}
}
文档:
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html
您可以为此使用 mapped type:
type FieldContainerInterface<T> = {
[key in keyof T]: FieldInterface;
}
我有这个interface
:
export interface FieldContainerInterface {
[key: string]: FieldInterface;
}
我想根据其他接口定义 key
字符串。我希望使用这样的东西:
interface FieldContainerInterface<T> {
// in here how can I pick the fields from <T>?
[T<key>: string]: FieldInterface;
}
interface BanknoteInterface {
id: number;
deviza_id: number;
value: string;
}
class Banknote implements BanknoteInterface {
id: number;
deviza_id: number;
value: string;
fieldContainer: FieldContainerInterface<BanknoteInterface> {
// here I MUST to define id, defiza_id and value fields
}
我能以某种方式定义 FieldContainerInterface
中的 key
字符串吗?
不确定您要实现的目标,但将键限制为特定值的一种方法是使用 keyof
运算符。 Here 是一篇关于它的好文章。示例:
import React from 'react';
interface BanknoteInterface {
id: number;
deviza_id: number;
value: string;
}
type FieldContainerInterface<T> = {
[key in keyof T]?: any;
}
class Banknote implements BanknoteInterface {
id: number;
deviza_id: number;
value: string;
fieldContainer: FieldContainerInterface<BanknoteInterface> = {
// optionally add any key
value: "hello",
// id: 5,
// deviza_id: 5
}
}
文档: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html
您可以为此使用 mapped type:
type FieldContainerInterface<T> = {
[key in keyof T]: FieldInterface;
}