Typescript 为typescrpit定义输出类型,以防止将输出参数误认为输入

Typescript 为typescrpit定义输出类型,以防止将输出参数误认为输入,typescript,Typescript,这可能已经定义好了,我是从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.r

这可能已经定义好了,我是从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=T;//这是我幼稚的实现,没有实现它的目的。
类型Result={Result:number};
函数myFun(a:编号,b:编号,c:函数输出)
{
c、 结果=a+b;
}
c:结果={};
//我应该如何定义FunctionOutput类型,以便下面的调用给出一个错误
myFun(1,2,c)//这应该会给出错误:c不是FunctionOutput类型
//这将强制调用函数,如下所示:
myFun(1、2、c作为函数输出);
console.log(c.result);//产出3
有了这一点,我想在函数调用时非常清楚地表明第三个参数是一个输出,我不希望用户能够调用第三个参数,认为它是一个输入参数。问题是:

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

Typescript有,所以通常一个类型不可分配给另一个类型,它必须具有另一个类型没有的属性。如果您希望像
FunctionOutput
这样的类型只能与类型断言
c as…
一起使用,那么您可以给它一个没有实际值的属性;例如:

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

c
对象在运行时当然不会真正具有
\uuu brand
属性,但您永远不会实际访问该属性,所以这无关紧要。

如果您只使用结果类型,问题中的代码有什么问题?在myFun(1,2,c)的情况下不会失败。如果传递的类型不是FunctionOutput类型,我希望它产生一个错误。我更新了这个问题,试图让它更清楚,这正是我所希望的答案。非常感谢您的解释和示例