现有的 JavaScript 代码有“记录”,其中 id 是数字,其他属性是字符串。尝试定义这种类型:
type t = {
id: number;
[key:string]: string
}
Run Code Online (Sandbox Code Playgroud)
给出错误 2411 id 类型编号无法分配给字符串
如何表达一个接口(IResponse),一个属性有一个字符串键(静态不知道).下面,键values可以是任何类似的books,chairs等等.所有其他键和类型都是静态已知的.以下实现给出错误.我猜错误是因为索引签名IResponse使所有属性值成为IValue[].有没有办法做到这一点?
export interface IMeta{}
export interface IValue{}
export interface IResponse {
meta: IMeta;
[index: string]:IValue[];
}
export class Response implements IResponse {
meta:IMeta;
values:IValue[];
//books:IValue[];
//anything:IValue[];
}
Run Code Online (Sandbox Code Playgroud) interface Foo {
bar: {};
[key: string]: string;
}
// Property 'bar' of type '{}' is not assignable to string index type 'string'.
Run Code Online (Sandbox Code Playgroud)
我试图使属性bar为Object字符串,任何其他属性为字符串,如何在没有 的情况下定义它any?
我正在尝试创建一种类型,其中一个字符串是一个对象,但每个其他字符串键都等于一个字符串。这是我尝试过的所有代码。
interface SubElement {
someProperty: string;
}
Run Code Online (Sandbox Code Playgroud)
'subElement'这是我想要在主对象的属性中使用的对象类型。
interface MainType1 {
[key: string]: string;
/* Error: Property 'subElement' of type 'SubElement' is not assignable to 'string' index type 'string'.ts(2411) */
subElement: SubElement;
}
Run Code Online (Sandbox Code Playgroud)
这个错误出现在接口声明中,并且它也作为类型而不是接口出现错误。
type MainType3 = {
/* Error: Property 'subElement' of type 'SubElement' is not assignable to 'string' index type 'string'.ts(2411) */
subElement: SubElement;
[key: Exclude<string, 'subElement'>]: string;
}
Run Code Online (Sandbox Code Playgroud)
这与第一个有相同的错误。
/* Type doesn't error */
type MainType2 = {
subElement: SubElement;
} & {
[key: string]: string; …Run Code Online (Sandbox Code Playgroud)