I extended a new class from the base class and added some properties. How to create an instance of a derived class using a given base class (including attached properties)?
This code works, but it casts the class type and is not type safe
// Base class is imported from a package. Not editable class BaseClass { public x: number; public power() { return this.x * 2; } } export interface CustomClass extends BaseClass { value: number; } function createCustomClass(base: BaseClass, myValue: number): CustomClass { // it's not type safe to cast this variable // How to do it the right way in Typescript? const result: CustomClass = base as CustomClass; result.value = myValue; return result; }
I don't think it's possible to rule out type conversion completely with your approach, but if you use
type Guard
to check if the variableresult
is validCustomClass
(in mine The implementation isisCustomClass
), that would be safe: p>You can use the
Object.assign ()
method to add properties to the target object. This method returns the target object, and its call signature in the TypeScript library that is the intersection of the input types.This means your
createCustomClass()
can be implemented like this:The return type is
BaseClass & {value: number}
, and its structure is the same asCustomClass
, so there will be no errors in function compilation, and there is no type assertion required.Playground code link p>