相关疑难解决方法(0)

可以使用约束“对象”的其他子类型实例化

在递归类型中有类型检查错误。

我正在尝试为react-jss样式对象编写类型。

type StylesFn<P extends object> = (
  props: P
) => CSS.Properties<JssValue<P>> | number | string;

type JssValue<P extends object> =
  | string
  | number
  | Array<string | number>
  | StylesFn<P>;

// @ts-ignore
interface StylesObject<K extends string = any, P extends object = {}>
  extends Styles {
  [x: string]: CSS.Properties<JssValue<P>> | Styles<K, P>;
}
export type Styles<K extends string = any, P extends object = {}> = {
  [x in K]: CSS.Properties<JssValue<P>> | StylesObject<any, P> | StylesFn<P>
};
Run Code Online (Sandbox Code Playgroud)

它工作正常,但打字稿会写错误。我使用@ …

typescript

17
推荐指数
2
解决办法
6993
查看次数

类型可分配给“类型”类型的约束,但“类型”可以使用约束“类型”的不同子类型进行实例化

已经有几个问题是这样问的。但我认为这更具体一点。

请看这个例子:

interface Body {
  legs: number;
}

interface Kingdom {
  animalia: {
    sound: string; // meow..
    body: Body;
  };
}

function GetBody<
  Category extends keyof Kingdom,
  B extends Kingdom[Category]["body"]
>(cat: Category): B {
  // stuff..
  return { legs: 4 }; // <==== Error!
}

// called like: GetBody('animalia').legs

Run Code Online (Sandbox Code Playgroud)

错误说:

Type '{ legs: number; }' is not assignable to type 'B'.
  '{ legs: number; }' is assignable to the constraint of type 'B', 
  but 'B' could be instantiated with a …
Run Code Online (Sandbox Code Playgroud)

typescript typescript-generics

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

标签 统计

typescript ×2

typescript-generics ×1