Returning extended custom object parameter from function in TypeScript and have VS intellisense show the extended properties

StackOverflow https://stackoverflow.com/questions/21967283

Question

The only way I can properly explain what I'm trying to do is by example:

function CustomExtend(myParam: Object): Object {
    return $.extend(myParam, { extraParameter: 'extraParam' });
}

I want intellisense when using the CustomExtend function to provide all the properties and methods of the object passed in plus the extraParameter property added inside the function. The closest I could get to getting this to work was by using generics and an interface:

interface IMyParamStructure {
    extraParameter?: string;
}

function CustomExtend<TParam extends IMyParamStructure>(myParam: TParam): TParam {
    myParam.extraParameter='extraParam';
    return myParam;
}

This works to a degree, it has intellisense correctly of all the properties and methods of the object passed in (myParam) but it still doesn't have the extraParameter property on the result. I expect this is because I made it optional and it wasn't passed in (because I don't want to have to pass it in). Is this just not possible with the TypeScript compiler?

EDIT: Forgot to add that the generic parameter should be inferred, not given, i.e. it would be used in this way:

var result=CustomExtend({ param1: 'something', param2: 'something else' });

What I want is for intellisense to show param1, param2 and extraParameter.

Was it helpful?

Solution

In TypeScript all type inference needs to be at compile time. TypeScript cannot modify interface definitions based on calling context.

This would require the ability to write code that runs within the compiler context with access to the AST which is not a planned feature at the moment.

Here is a related stackoverflow question : Is it possible to model jQuery.fn.extend using TypeScript

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top