相关疑难解决方法(0)

如何将 Typescript 类型定义为字符串字典,但具有一个数字“id”属性

现有的 JavaScript 代码有“记录”,其中 id 是数字,其他属性是字符串。尝试定义这种类型:

type t = {
    id: number;
    [key:string]: string
}
Run Code Online (Sandbox Code Playgroud)

给出错误 2411 id 类型编号无法分配给字符串

typescript

16
推荐指数
1
解决办法
1278
查看次数

具有未知属性键的typescript接口定义

如何表达一个接口(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)

typescript

9
推荐指数
2
解决办法
8563
查看次数

如何定义一种不同于其他任何类型的财产类型?

interface Foo {
  bar: {};
  [key: string]: string;
}

// Property 'bar' of type '{}' is not assignable to string index type 'string'.
Run Code Online (Sandbox Code Playgroud)

我试图使属性barObject字符串,任何其他属性为字符串,如何在没有 的情况下定义它any

typescript typescript-typings

5
推荐指数
1
解决办法
1012
查看次数

如何从所有字符串中排除字符串类型

我正在尝试创建一种类型,其中一个字符串是一个对象,但每个其他字符串键都等于一个字符串。这是我尝试过的所有代码。

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)

typescript typescript-typings

5
推荐指数
0
解决办法
1156
查看次数

标签 统计

typescript ×4

typescript-typings ×2