这种行为是Typescript 2.0.3中的错误吗?我怎样才能改进功能定义?
function cleanString<T>(path: T): T {
if (path === null || path === undefined || typeof path !== 'string') {
return path;
}
return path.replace(/\\+/g, '/'); // <- path is never here
}
预期行为 应该编译没有问题
实际行为
<{1}}在最后一行是path
。
never
可以工作,但会丢失(输入类型==输出类型)信息。
function cleanString(path: any)
有效,但不优雅。
基于Nitzan Tomer的想法,我发现:
(<any>path)
答案 0 :(得分:1)
你需要做一些演员:
function cleanString<T>(path: T): T {
if (path === null || path === undefined || typeof path !== 'string') {
return path;
}
return (path as string).replace(/\\+/g, '/') as any;
}
let num = cleanString(3); // type of num is number
let bool = cleanString(true); // type of bool is boolean
let str = cleanString("string"); // type of str is string
如果您不喜欢any
的使用,如果T
可以是一组有限的类型,那么您可以这样做:
function clean(path: string): string;
function clean(path: boolean): boolean;
function clean(path: number): number;
function clean(path) {
if (typeof path === "string") {
return path.replace(/\\+/g, '/');
}
return path;
}
let num = clean(3); // type of num is number
let bool = clean(true); // type of bool is boolean
let str = clean("string"); // type of str is string