Cast object to interface in TypeScript

typescript interface array
typescript interface constructor
typescript as
typescript convert object to class
typescript mapped object type
typescript export interface
cast object to array typescript
typescript types

I'm trying to make a cast in my code from the body of a request in express (using body-parser middleware) to an interface, but it's not enforcing type safety.

This is my interface:

export interface IToDoDto {
  description: string;
  status: boolean;
};

This is the code where I'm trying to do the cast:

@Post()
addToDo(@Response() res, @Request() req) {
  const toDo: IToDoDto = <IToDoDto> req.body; // <<< cast here
  this.toDoService.addToDo(toDo);
  return res.status(HttpStatus.CREATED).end();
}

And finally, the service method that's being called:

public addToDo(toDo: IToDoDto): void {
  toDo.id = this.idCounter;
  this.todos.push(toDo);
  this.idCounter++;
}

I can pass whatever arguments, even ones that don't come close to matching the interface definition, and this code will work fine. I would expect, if the cast from response body to interface is not possible, that an exception would be thrown at runtime like Java or C#.

I have read that in TypeScript casting doesn't exist, only Type Assertion, so it will only tell the compiler that an object is of type x, so... Am I wrong? What's the right way to enforce and ensure type safety?


There's no casting in javascript, so you cannot throw if "casting fails". Typescript supports casting but that's only for compilation time, and you can do it like this:

const toDo = <IToDoDto> req.body;
// or
const toDo = req.body as IToDoDto;

You can check at runtime if the value is valid and if not throw an error, i.e.:

function isToDoDto(obj: any): obj is IToDoDto {
    return typeof obj.description === "string" && typeof obj.status === "boolean";
}

@Post()
addToDo(@Response() res, @Request() req) {
    if (!isToDoDto(req.body)) {
        throw new Error("invalid request");
    }

    const toDo = req.body as IToDoDto;
    this.toDoService.addToDo(toDo);
    return res.status(HttpStatus.CREATED).end();
}

Edit

As @huyz pointed out, there's no need for the type assertion because isToDoDto is a type guard, so this should be enough:

if (!isToDoDto(req.body)) {
    throw new Error("invalid request");
}

this.toDoService.addToDo(req.body);

Typescript - How to cast object to interface, Interfaces don't exist at runtime. Your best option would be delete unwanted properties yourself or create a copy of the object with the  You can find more about it in the TypeScript Language Specification: 4.19.4 The instanceof operator. The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, and the right operand to be of type Any or a subtype of the ‘Function’ interface type. The result is always of the Boolean


Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:

export function forceCast<T>(input: any): T {

  // ... do runtime checks here

  // @ts-ignore <-- forces TS compiler to compile this as-is
  return input;
}

Then you can use it to force cast objects to a certain type:

import { forceCast } from './forceCast';

const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);

Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts interface files into JSON schemas and using ajv to validate in runtime.

Typescript: cast an object to other type. How? And instanceof or , Typescript: cast an object to other type. parameter type, and the right operand to be of type Any or a subtype of the 'Function' interface type. In Typescript, there are two types of objects. Plain objects: When we try to parse JSON data using JSON.parse() method then we get a plain object and not a class object. Class(constructor) objects: A class object is an instance of a Typescript class with own defined properties, constructors and methods. Example:


If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

Type Assertion in TypeScript, It is similar to type casting in other languages like C# and Java. Similarly, we might have a situation where we have an object that has been declared without interface Employee { name: string; code: number; } let employee = <Employee>  In my previous article, Learned how to declared and implement typescript interfaces. This conversion is required to know as Front applications coded in typescript calls REST API which calls backend services, returns the response in JSON format. This JSON object needs to transfer to interface/class to bind this data to UI.


Interfaces in TypeScript: What are they and how do we use them , Here come TypeScript interfaces to help! Object literal may only specify known properties, and measureRemCharging does not exist in type  JavaScript doesn’t have a concept of type casting because variables have dynamic types. However, every variable in TypeScript has a type. Type castings allow you to convert a variable from one type to another. In TypeScript, you can use the askeyword or <>operator for type castings.


Type casting in Typescript – Techformist, From object to array. Yes, you read that right - let's see an example of converting object to array in style. Not quite a glaring  Interface in Typescript is used to tell the compiler what the shape of the JS object should look like. It is a compile time construct hence it will not have generated code as type checking in Typescript is only done at compile time rather than runtime.


Mapping JSON from API call to TypeScript classes, On past projects (without TypeScript), I've always just used the JSON objects the cast would give me an object that actually implemented the interface. { status:​  An interface can be extended by other interfaces. In other words, an interface can inherit from other interface. Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces. Syntax: Single Interface Inheritance Child_interface_name extends super_interface_name