0

这可能已经定义了,我从 C# 得到这个想法。我想写以下内容:

type FunctionOutput<T> = T; // This is my naive implementation, which doesn't fulfill its purpose.
type Result = {result: number};

function myFun(a: number, b: number, c: FunctionOutput<Result>)
{
   c.result = a + b;
}

c: Result = {};
// How should I define FunctionOutput type so that the following call gives an error
myFun(1, 2, c) // This should give Error: c is not of type FunctionOutput<Result>

// This would enforce calling the function as follows:
myFun(1, 2, c as FunctionOutput<Result>);
console.log(c.result);   // Outputs 3

有了这个,我想在函数调用中非常清楚地表明第三个参数是一个输出,我不希望用户能够调用这个第三个参数,认为它是一个输入参数。问题是:

我应该如何定义这种FunctionOutput类型?

4

1 回答 1

1

Typescript 具有结构类型,因此通常一种类型不能分配给另一种类型,它必须具有另一种类型没有的属性。如果你想要一个类型FunctionOutput<T>只能用于类型断言c as ...,那么你可以给它一个没有真正价值的属性;例如:

type FunctionOutput<T> = T & { __brand: 'FunctionOutput' }

当然,c对象在运行时不会真正拥有该__brand属性,但您永远不会真正访问该属性,所以没关系。

于 2020-11-27T13:26:22.733 回答