从接口推断出的泛型的返回类型

时间:2019-09-26 09:22:26

标签: typescript interface typescript-generics

我正在通过字符串文字联合类型描述接口的所有可用方法。
然后用它来描述接口。

然后我从该接口推断任何给定方法的返回类型,该返回类型应始终为boolean

以某种方式TypeScript认为它并不总是布尔值,但是我不知道为什么以及如何更改类型以更清楚地表达我想要的内容。

export type method = 'add' | 'get';

export type intfce = { [M in method]: () => boolean };
// => { add: () => boolean; get: () => boolean; }

export type ret<M extends method> = ReturnType<intfce[M]>;
export type retAdd = ret<'add'>;  // => boolean
export type retGet = ret<'get'>;  // => boolean

export function fn<M extends method>(): ret<M> {
  return true;  // Error: Type 'true' is not assignable to type 'ReturnType<intfce[M]>'.
}
export function fn2(): boolean {
  return true;  // OK
}

我已经搜索了很多答案,但是似乎很难准确描述我要做什么并找到答案。

我最好的猜测是,在function fn<M extends method>的情况下,M可能不只是'add' | 'get'
所以我尝试了:

const resAdd = fn<'add'>(); // OK
const resGet = fn<'get'>(); // OK
const resPut = fn<'put'>(); // Error: Type '"put"' does not satisfy the constraint 'method'.
const resToString = fn<'toString'>(); // Error: Type '"toString"' does not satisfy the constraint 'method'.
const resEmpty = fn<''>(); // Error: Type '""' does not satisfy the constraint 'method'.
const resNull = fn<null>(); // Error: Type 'null' does not satisfy the constraint 'method'.
const resUndefined = fn<undefined>(); // Error: Type 'undefined' does not satisfy the constraint 'method'.
const resNumber = fn<0>();  // Error: Type '0' does not satisfy the constraint 'method'.
const resObj = fn<{}>();  // Error: Type '{}' does not satisfy the constraint 'method'.

由此产生的错误表明确实只有'add' | 'get'是可能的,这使我回到平方1 ...


我试过ReturnType是否是罪魁祸首,的确如此,因为下面的代码没有错误:

export type intfce2 = { [M in method]: boolean };
export type ret2<M extends method> = intfce2[M];
export type retAdd2 = ret2<'add'>;  // => boolean
export type retGet2 = ret2<'get'>;  // => boolean

export function fn3<M extends method>(): ret2<M> {
  return true;  // Error: Type 'true' is not assignable to type 'ReturnType<intfce[M]>'.
}

如何(重新)定义ReturnType才能使初始代码起作用?

0 个答案:

没有答案