How to add a property to an existing object to satisfy an interface in typescript?

typescript extend interface
typescript object key type
typescript add property to interface
add property to array of objects typescript
js add property to existing object
typescript create new object from existing object
typescript add key to object
add parameter to object typescript

Here's what I would like to do in a nutshell:

interface A {
     prop1: string;
}

interface B extends A {
    prop2: string;
}

someImportantFunction(x: A): B {
    var ret: B = x.prop2 = someCalculation(); //Error, but if possible x would now satisfy B

    return ret;
}

The english version of my question is: how can I add new properties to an existing object in typescript, with the goal of satisfying a more-derived interface definition? Perhaps this is not possible, or I am missing some obvious approach.

UPDATE: Also, suppose the list of properties on interface A is long, so boilerplate assignment by mapping properties is laborious and not clean.

I also see something like this would work, but it seems like a hack:

someImportantFunction(x: A): B {
    var ret: B = <B>x;
    ret.prop2 = someCalculation();

    return ret;
}

Thanks, Mathias

With intersection types (TS 1.6+), you can have more type safety:

// your typical mixin function, like lodash extend or jQuery.extend
// you can use one of those instead of this quick and dirty implementation,
// the main reason for having this function is its type signature
function extend<T1, T2>(source: T1, addition: T2): T1 & T2 {
  let result = <T1 & T2>source;
  for(let key of Object.keys(addition)) {
    result[key] = addition[key];
  }
  return result;
}

interface A {
  prop1: string;
}

interface B extends A {
  prop2: string;
}

function someImportantFunction(x: A): B {
  return extend(x, {
    prop2: someCalculation()
  });
}

This way the compiler can determine what properties of type B are missing from type A and ensure your extend call provides them.

How to Add, Modify, or Access JavaScript Object Literal Properties, How do I add a new property to an object in TypeScript? This interface will accept any property name with any value attached. Conclusion. In conclusion, you can’t actually add properties to an interface dynamically. But, you can get a similar effect using extends, on-the-fly Intersection types, or interfaces with variable keys.

Use Object.assign:

interface A { prop1: string; }
interface B extends A { prop2: string; }

someImportantFunction(x: A): B {
    var ret: B = Object.assign(x, { prop2 : someCalculation()});

    return ret;
}

The types come out because of the typing file defines the return values as an intersection type (&):

assign<T, U>(target: T, source: U): T & U;

TypeScript Interface, In Typescript, an interface can be used to describe an Object's required properties along with their types. Now create an ordinary JavaScript object with same properties. Please whitelist our site or disable adds blocker to support us. Jackson JSON - Updating Existing objects with JSON input during  1. With an interface. To add a new property and prevent any compile error, you can use an interface to describe the Window with your new property. In TypeScript, interfaces fill the role of naming types, and are a powerful way of defining contracts within your code as well as contracts with code outside of your project.

It's more a JavaScript-Problem:

function someImportantFunction(x: A): B {
    var ret: B = {
        prop1: x.prop1,
        prop2: someCalculation()
    }

    return ret;
}

but you could also do:

function someImportantFunction(x: A): B {
    var ret: B = <B>x
    x.prop2 = someCalculation()

    return ret;
}

Typescript: is not assignable to type error, Object literal may only specify known properties, and Please note interfaces deal only with the instance part of the class. Generics in TypeScript are used when we have to create generic components that can work on  Interfaces are capable of describing the wide range of shapes that JavaScript objects can take. In addition to describing an object with properties, interfaces are also capable of describing function types. To describe a function type with an interface, we give the interface a call signature.

TypeScript - Using Interfaces to describe Object Properties, Adding a string indexer to the type will disable extra property checking have problems with object literals in our own compiler satisfying interfaces with TypeScript 1.6 breaking changes and gulp-typescript versioning #202. TypeScript - Interface Extending Interfaces [Updated: Sep 13, 2018, Created: Sep 13, 2018] Previous Page Next Page

Interfaces in TypeScript: What are they and how do we use them , string; objectMember: X; // Where X is a inline object type, interface, or other This way we wouldn't need to create a sibling interface just to hold the same properties with I should have linked to : https://github.com/Microsoft/TypeScript/​wiki/ Please note that Partial<T> is now part of the default library file. The TypeScript compiler implements the duck-typing system that allows object creation on the fly while keeping type safety. The following example shows how we can pass objects that don’t explicitly implement an interface but contain all of the required members to a function.

Error when 'extra' properties appear in object literals · Issue #3755 , These optional properties are popular when creating patterns like “option bags” where you pass an object to a function  However, there are several things that I struggle with using Typescript, the biggest one is using a method on an object that isn't in the Typescript definition file or a property you have added to a custom object. Extending Leaflet Definitions. I have run into this several times using Angular and the Leaflet Angular directive. The Leaflet

Comments
  • The accepted answer that utilizes intersection types performs this operation in a type-safe manner. The approach you outlined does not guarantee that adding "prop2" to x results in an object that satisfies type B.
  • @mathias999us: It does though. Object.assign is defined as assign<T, U>(target: T, source: U): T & U;, almost identically to the accepted answer.
  • @mathias999us updated the answer - you should be able to now =)
  • I independently verbatim updated my post with your second solution at the same time that you provided it. If it turns out that this is truly the best/only solution (which I'm thinking it is), I will accept your answer.
  • @mathias999us I also hope there is a more typesafe solution, but I can't think of one (the first would be the best typesafe solution, but remember the 2nd will return the same object x, not a copy of it, the first will return a copy of it)