为什么不能分配(打字稿)泛型。如何解决

时间:2020-11-12 09:12:58

标签: typescript generics

vertical-align: middle;aa

不兼容
A

上面构造的一些问题无法表达该问题,但是这个问题确实存在:

interface A<T, P> {
    b?: (input:T) => T
    c?: (input:P) => P
}

interface B extends A<number, string> {}

const aa: B = {
    // (property) A<number, string>.c?: ((input: string) => string) | undefined
    // Type 'string' is not assignable to type '((input: string) => string) | undefined'.(2322)
    // input.tsx(31, 5): The expected type comes from property 'c' which is declared here on type 'B'
    c: 'xxx'
}

interface HttpResponse<T = any> { ok: boolean; data: T; status: number; statusText: string; headers: any; usingCache?: boolean; } declare class HttpError extends Error { __hRestHttpError: boolean; name: 'HttpError'; code: number; status: number; constructor(message: any); } const all: HttpError | HttpResponse<any> = { // Type '{ return: HttpError; }' is not assignable to type 'HttpError | HttpResponse<any>'. Object literal may only specify known properties, and 'return' does not exist in type 'HttpError | HttpResponse<any>'. return new HttpError('dd') } 分配给typeA

1 个答案:

答案 0 :(得分:0)

在您的界面中,您确定c是一个函数,接受类型为P的输入并返回类型为P。在c中分配一个字符串值。我不确定您的用例是什么,但是如果确实是一个函数,则可以通过以下方式解决此问题:

interface A<T, P> {
  b?: (input: T) => T;
  c?: (input: P) => P;
}

interface B extends A<number, string> {}

const aa: B = {
  // (property) A<number, string>.c?: ((input: string) => string) | undefined
  // Type 'string' is not assignable to type '((input: string) => string) | undefined'.(2322)
  // input.tsx(31, 5): The expected type comes from property 'c' which is declared here on type 'B'
  c: (input: string) => 'xxx',
};

另一方面,如果您希望c为字符串,则可以通过

对其进行解析。
interface A<T, P> {
  b?: (input: T) => T;
  c?: P;
}

interface B extends A<number, string> {}

const aa: B = {
  // (property) A<number, string>.c?: ((input: string) => string) | undefined
  // Type 'string' is not assignable to type '((input: string) => string) | undefined'.(2322)
  // input.tsx(31, 5): The expected type comes from property 'c' which is declared here on type 'B'
  c: 'xxx',
};
相关问题