在我的typescript项目中,我创建了一个自定义类(灵感来自rust's
Result<T, E>
(顺便说一句)看起来是这样的:
export class Result<T, E extends Error = Error>
{
public errors: E[] = [];
public result: T | null = null;
public static ok<T, E extends Error>(result: T): Result<T, E>
{
return new Result(result, [] as E[]);
}
public static err<T, E extends Error>(...errors: E[]): Result<T, E>
{
return new Result<T, E>(null as unknown as T, errors);
}
public static apiErr<T>(...errors: ApiErrorKind[]): Result<T, ApiError>
{
return new Result<T, ApiError>(null as unknown as T, errors.map(e => new ApiError(e)));
}
private constructor(result: T | null, errors: E[])
{
this.result = result;
this.errors = errors;
}
public and<T2, E2 extends Error = E>(f: (x: T) => Result<T2, E2>): Result<T2, E | E2>
{
if (this.isErr)
return Result.err(...this.errors);
let errors: (E | E2)[] = this.errors;
try
{
return f(this.result as T);
}
catch (e)
{
errors.push(e as E2);
}
return Result.err(...errors);
}
// irrelevant methods omitted for brevity
public then<T2, E2 extends Error = E>(f: (x: T | null) => T2): Result<T2, E | E2>
{
if (this.isErr)
return Result.err(...this.errors);
let errors: (E | E2)[] = this.errors;
try
{
return Result.ok(f(this.result));
}
catch (e)
{
errors.push(e as E2);
}
return Result.err(...errors);
}
}
然而,每当我尝试使用它时,我总是会得到关于空值转换的神秘错误,尽管没有任何错误
null
在望:
export async function createUser(input: UserInput, organization: string): Promise<Result<User, ApiError>>
{
const validation = validateUser(input); // returns Result<boolean, ApiError>
if (validation.isErr)
return Result.err<User, ApiError>(... validation.errors); // Error on this line
}
TS23 22
类型“user null”不能分配给类型“result”。类型“null”不能分配给类型“result”。
为什么会这样?