无法调用类型缺少调用签名的表达式。类型没有兼容的呼叫签名

时间:2017-05-01 23:34:02

标签: typescript

我试图为docuri

制定定义
export type URI<K extends RouteParams> = string;

export interface RouteParams {
  [key: string]: (string | number | boolean)
}

export interface Document {
  [key: string]: (string | number | boolean)
}

/**
 * Create a URI from a document properties
 * @param the props to build the URI from
 * @return the URI
 */
export type RouteCreator<K extends RouteParams> = (props: K) => string;

/**
 * Parses a URI and returns the props
 * @param uri the URI to parse
 * @return the params parsed from URI
 */
export type RouteParser<K extends RouteParams> = (uri: string) => K;

export type Route<T extends RouteParams> = RouteParser<T> | RouteCreator<T>;

/**
 * Creates a Route which is a function that either parse or stringify object/string
 * @param route the route uri
 * @return the Route
 */
export type RouteFactory<K extends RouteParams> = (route: string) => Route<K>;

export interface DocURI<K extends RouteParams> {
  route: RouteFactory<K>;
}

然后使用它:

import {DocURI, Document, RouteParams, URI, RouteFactory} from './Definitions';

const docuri = require('docuri');

function getRoute <T extends Document> (): DocURI<T> {
  return (docuri as DocURI<T>);
}
...
const artistURI = getRoute<ArtistParams>().route('artist/name');

const parsed = artistURI(album.artist); // Cannot invoke an expression whose type lacks a call signature. Type 'Route<ArtistParams>' has no compatible call signatures.

我接上了最后一行:

 Cannot invoke an expression whose type lacks a call signature. Type 'Route<ArtistParams>' has no compatible call signatures.

我做错了什么?

1 个答案:

答案 0 :(得分:3)

查看此问题:Call signatures of union types

  

这是目前的设计,因为我们没有合成   获取联合类型成员时的交叉调用签名    - 仅在联合类型上显示相同的呼叫签名

所以现在你需要让两个函数签名相同,或者转换结果:

const artistURI = getRoute<ArtistParams>().route('artist/name') as (str: string) => string;

const parsed = artistURI(album.artist); // should be ok