我想做一个也可以返回值的asserts风格的保护子句。这个是可能的吗?这就是我的梦想。
// this return type gives a compiler error
export function assertString(input: any): ((asserts input is string) & string) {
if (typeof input != "string") throw "Expected string, got " + input;
return input;
}它可以被灵活地使用。
function getLength(arg: any) {
assertString(arg);
return arg.length;
}
// but also
function getLength2(arg: any) {
return assertString(arg).length;
}这在typescript中是可能的吗?
发布于 2020-04-16 03:01:10
截至今天(2020年4月15日),答案是否定的。
有一个GitHub问题https://github.com/microsoft/TypeScript/issues/34636
在此问题解决之前,您可以使用条件返回类型,如下所示:
function assertString<T>(input: T): T extends string ? string : never {
if (typeof input !== "string") throw "Expected string, got " + input;
return (input as any);
}

https://stackoverflow.com/questions/61235732
复制相似问题