乐闻世界logo
搜索文章和话题

How do i cast a json object to a typescript class

6个答案

1
2
3
4
5
6

To convert a JSON object into a TypeScript class, you can define a class whose properties and types correspond to the keys and values of the JSON object. Here's a simple example demonstrating this process.

Assume we have the following JSON object:

json
{ "id": 1, "name": "Alice", "email": "alice@example.com", "isActive": true }

We can create a TypeScript class to represent this JSON object:

typescript
class User { id: number; name: string; email: string; isActive: boolean; constructor(id: number, name: string, email: string, isActive: boolean) { this.id = id; this.name = name; this.email = email; this.isActive = isActive; } }

To instantiate a JSON object as an instance of this class, we can write a function to handle the conversion:

typescript
function createUser(json: any): User { return new User(json.id, json.name, json.email, json.isActive); } // JSON object const json = { "id": 1, "name": "Alice", "email": "alice@example.com", "isActive": true }; // Convert JSON object to User class instance const user = createUser(json);

Here are some additional considerations:

  1. Type validation: In practical applications, you may need to verify that the JSON object contains all required properties and that their types are correct. TypeScript's type system provides compile-time assistance, but at runtime, you may need additional validation.

  2. Optional properties: If certain properties in the JSON object may be missing, mark them as optional in the TypeScript class. For example:

typescript
class User { id: number; name: string; email: string; isActive?: boolean; // Optional property // If isActive is optional, the constructor parameter should also be marked as optional constructor(id: number, name: string, email: string, isActive?: boolean) { this.id = id; this.name = name; this.email = email; this.isActive = isActive; } }
  1. Complex objects: If your JSON object contains nested objects or arrays, ensure the corresponding TypeScript types reflect this structure.

  2. Automation: If you frequently perform this conversion, consider using automation tools such as quicktype or other online converters that generate TypeScript type definitions from JSON input.

2024年6月29日 12:07 回复

I found a very interesting article about mapping JSON to TypeScript interfaces: http://cloudmark.github.io/Json-Mapping/

You will eventually get the following code:

typescript
let example = { "name": "Mark", "surname": "Galea", "age": 30, "address": { "first-line": "Some where", "second-line": "Over Here", "city": "In This City" } }; MapUtils.deserialize(Person, example); // custom interface
2024年6月29日 12:07 回复

If you are using ES6, try the following:

typescript
class Client{ name: string displayName(){ console.log(this.name) } } service.getClientFromAPI().then(clientData => { // Here, the client data from the API only has the 'name' field // To use the Client class methods on this data object, you need to: let clientWithType = Object.assign(new Client(), clientData) clientWithType.displayName() })

Unfortunately, this method does not apply to nested objects.

2024年6月29日 12:07 回复

In TypeScript, you can use interfaces and generics for type assertions, as shown below: type assertion

shell
var json = Utilities.JSONLoader.loadFromFile("../docs/location_map.json"); var locations: Array<ILocationMap> = JSON.parse(json).location;

The ILocationMap interface describes the data structure. This approach allows your JSON to include additional properties, provided the shape adheres to the interface.

However, this does not add instance methods to the class.

2024年6月29日 12:07 回复

I encountered the same issue. I found a library that can handle this conversion: https://github.com/pleerock/class-transformer.

Here's how it works:

typescript
let jsonObject = response.json() as Object; let fooInstance = plainToClass(Models.Foo, jsonObject); return fooInstance;

It supports nested objects, but you must decorate your class members with decorators.

2024年6月29日 12:07 回复

You cannot simply convert the plain JavaScript result from an Ajax request into a JavaScript/TypeScript class instance. There are multiple techniques to achieve this, and they typically involve copying data. Unless you create an instance of the class, it will not have any methods or properties. It will still be a simple JavaScript object.

Although if you're only handling data, you can cast it to an interface (as it's purely a compile-time construct), this requires using a TypeScript class that utilizes the data instance and performs operations on the data.

Some examples of copying data:

  1. Copy an AJAX JSON object into an existing object
  2. Parse a JSON string into a specific object instance in JavaScript

Essentially, you just need to:

javascript
var d = new MyRichObject(); d.copyInto(jsonResult);
2024年6月29日 12:07 回复

你的答案