Home > Blockchain >  What value I can assign to "context"
What value I can assign to "context"

Time:03-26

I have a JSON string as shown below:

  "authConfig": {
      "context": "internal",
      "environment": "local",
    },

Meanwhile, the type of authConfig is

export interface AuthConfig<APP = App> {
    environment?: TokenEnv;
    context: AuthContext;

}

And also the AuthContext is:

export declare type AuthContext = 'internal' | 'external';

However, when I use the JSONS string in my test file, it shows the below error:

The types of 'authConfig.context' are incompatible between these types. Type 'string' is not assignable to type 'AuthContext'.ts(2345)

May I please know what the value I can assign to context in JSON object to resolve this type issue? Thanks

CodePudding user response:

Typescript is inferring the types from your json file, however when it sees a property with a string value it just infers type string, rather than inferring the type as a string literal const type. As far as I know, json type-inferrence doesn't provide string literal types, I guess the rationale being nothing is stopping a different string being assigned to that key.

You will have to write your own type-guard or type-checker function to ensure that the key you're tying to access fits the specific string you're expecting. If you don't care about type-safety so much, just cast the string to what you're expecting (const foo = authConfig as AuthConfig). Typescript should still tell you if the object shapes don't match up enough to be cast.

Alternately, if you can you could always move from json to js as your data-storage method. This can be ES5 compatible if that's what you need, and by turning on the allowJS and checkJS flags in your tsconfig you can get the type-inference you need. The big benefit is with js you can specify strings as const type using jsdoc type comments, which are interpreted by typescript.

const foo = /** @type {const} */ ({x: 1});
const bar = /** @type {const} */ ("baz");

EDIT: found some other interesting links for other potential approaches / features to watch: https://www.reddit.com/r/typescript/comments/k57xgc/how_to_infer_types_from_json_file/ https://github.com/microsoft/TypeScript/issues/32063

  • Related