属性 不可分配给接口中的字符串索引
Property is not assignable to string index in interface
我有以下接口:
export interface Meta {
counter: number;
limit: number;
offset: number;
total: number;
}
export interface Api<T> {
[key: string]: T[];
meta: Meta; // error
}
目前,我收到以下错误:
Property 'meta' of type 'Meta' is not assignable to string index
type 'T[]'.
经过一番搜索,我在TS docs中找到了这条语句:
While string index signatures are a powerful way to describe the
“dictionary” pattern, they also enforce that all properties match
their return type. This is because a string index declares that
obj.property is also available as obj["property"].
这是否意味着当我有一个字符串索引签名时,我不能有任何其他不匹配此类型的变量?
实际上我可以像这样声明接口来消除这个错误:
export interface Api<T> {
[key: string]: any; // used any here
meta: Meta;
}
这样做,我完全失去了类型推断的能力。没有这种丑陋的方式,有什么办法可以做到这一点吗?
您可以使用两个接口的 intersection:
interface Api<T> {
[key: string]: T[];
}
type ApiType<T> = Api<T> & {
meta: Meta;
}
declare let x: ApiType<string>;
let a = x.meta // type of `a` is `Meta`
let b = x["meta"]; // type of `b` is `Meta`
let p = x["someotherindex"] // type of `p` is `string[]`
let q = x.someotherindex // type of `q` is `string[]`
当我尝试实现此接口时,所提供的最佳解决方案不起作用。我最终用动态键嵌套了一部分。也许有人会发现它有用:
interface MultichannelConfiguration {
channels: {
[key: string]: Configuration;
}
defaultChannel: string;
}
我有以下接口:
export interface Meta {
counter: number;
limit: number;
offset: number;
total: number;
}
export interface Api<T> {
[key: string]: T[];
meta: Meta; // error
}
目前,我收到以下错误:
Property 'meta' of type 'Meta' is not assignable to string index type 'T[]'.
经过一番搜索,我在TS docs中找到了这条语句:
While string index signatures are a powerful way to describe the “dictionary” pattern, they also enforce that all properties match their return type. This is because a string index declares that obj.property is also available as obj["property"].
这是否意味着当我有一个字符串索引签名时,我不能有任何其他不匹配此类型的变量?
实际上我可以像这样声明接口来消除这个错误:
export interface Api<T> {
[key: string]: any; // used any here
meta: Meta;
}
这样做,我完全失去了类型推断的能力。没有这种丑陋的方式,有什么办法可以做到这一点吗?
您可以使用两个接口的 intersection:
interface Api<T> {
[key: string]: T[];
}
type ApiType<T> = Api<T> & {
meta: Meta;
}
declare let x: ApiType<string>;
let a = x.meta // type of `a` is `Meta`
let b = x["meta"]; // type of `b` is `Meta`
let p = x["someotherindex"] // type of `p` is `string[]`
let q = x.someotherindex // type of `q` is `string[]`
当我尝试实现此接口时,所提供的最佳解决方案不起作用。我最终用动态键嵌套了一部分。也许有人会发现它有用:
interface MultichannelConfiguration {
channels: {
[key: string]: Configuration;
}
defaultChannel: string;
}