Sam
Sam

Reputation: 582

Stringified Type in Typescript

I feel like maybe I'm just not thinking this through clearly so forgive me if that's the case. Here's the problem:

I'm receiving exceptions formatted in a particular fashion. At the root of the error object I get your basic stuff: message, status, etc. However there's also a property call error which is a stringified object. When I create a type to model this error object, I'd like to not call that error property a 'string', that feels silly and not representative. However, that seems to be the only way I can define that property. (I realize it is a string, but that's the JSON equivalent to a type of any.)

My obvious expectation was that I could do something like Stringified<ParsedErrorProperty> (or something). That way when I receive that error object intellisense expects me to parse that property in order to access the attributes of that property, will know what attributes to expect post-parse, and will pitch a fit if I fail to do so.

Upvotes: 4

Views: 6201

Answers (2)

James Bond
James Bond

Reputation: 2966

You can use an index signature to type a stringified object.

type Stringified<T> = {
    [P in keyof T]: string
};

interface Obj {
  value: number
}

const test : Stringified<Obj> = {
  value: "string"
}

Upvotes: 2

basarat
basarat

Reputation: 276199

My obvious expectation was that I could do something like Stringified (or something).

You'll need to create your own Stringified and PrasedErrorProperty along with function parseError(error:string): Stringified<ParsedErrorProperty>.

This is not provided natively.

Upvotes: 1

Related Questions