Home > Mobile >  Typescript requirement to pass all variables
Typescript requirement to pass all variables

Time:03-31

i Work with ts-jest and i trie to mock one service function but i only need pass one variable values of many others. like the exemple below:

getDataInformationMocked.mockReturnValueOnce({
      scopes: ['local','cloud']
    });

this code works, but ts show a error saing it is more variables that are not being passed.

error message: The type '{ scopes: string[]; }' does not have the following properties of type 'dataNames': iss, exp, nbf, aud and 20 more.

so, is there any way to pass all variables from an interface, without having to create an object with all values?

CodePudding user response:

This builds off the playground provided by Charles Fries and both solutions resolve the error.

You can use either Partial which Constructs a type with all properties of Type set to optional. This utility will return a type that represents all subsets of a given type.:

interface DataNames {
    scopes: string[];
    iss: string;
    exp: string;
    nbf: string;
    aud: string;
}

const getDataInformationMocked = {
    mockReturnValueOnce: (_dataNames: Partial<DataNames>): void => {}
};

getDataInformationMocked.mockReturnValueOnce({
    scopes: ['local','cloud']
});

Or Pick which Constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type.:

interface DataNames {
    scopes: string[];
    iss: string;
    exp: string;
    nbf: string;
    aud: string;
}

const getDataInformationMocked = {
    mockReturnValueOnce: (_dataNames: Pick<DataNames, 'scopes'>): void => {}
};

getDataInformationMocked.mockReturnValueOnce({
    scopes: ['local','cloud']
});

CodePudding user response:

Use a type assertion:

getDataInformationMocked.mockReturnValueOnce({
  scopes: ['local','cloud']
} as dataNames);
  • Related