1

I want to implement type-checking of function arguments, where properties of second argument are based on properties of previous one.

The config variable should contain only such properties that are present in objects in values array. Properties should be optional (it is not needed to have all of them in config, but it is not allowed to add different ones.

Please, see the example code:

type CustomType <T> = {
  [K in keyof T]: number
};
type Config <T> = {
  [K in keyof T]? : {
    highPriority: boolean;
    callback: (values: any[]) => number[];
  }
};

const customFunction = <T>(values: T[], config: Config <T> ): Array <CustomType<T>> => {
  // logic...

  return [];
};

const values = [
  {
    foo: 'foo',
    bar: 'bar'
  },
  {
    foo: 'foo',
    bar: 'bar'
  }
];

// Should optionaly contain only "foo", "bar" properties in this example
const config = {
  foo: {
    highPriority: true,
    callback: () => []
  },
  // not present in values objects
  wrong: {
    highPriority: true,
    callback: () => []
  }
};

// config should be marked with errors as "wrong" is not present in values objects
const result = customFunction(values, config);

In the last line, config should be marked as error, because it introduces wrong property, which is not present in original values object.


I can force some checking with implementing an interface to the config, however I think it's unnecessary and that it could be done without it.

interface ISpecific {
  foo: any,
  bar: any
}

const values: ISpecific[] = [
  {
    foo: 'foo',
    bar: 'bar'
  },
  {
    foo: 'foo',
    bar: 'bar'
  }
];

const config: Config<ISpecific> = {
  // ...
  // wrong property is marked as error
}

UPDATED:

  • config is defined elsewhere and doesn't know about values variable
  • customFunction is used in several places across the application so passing the config as object literal is not viable.

Any help?

4
  • Side note: your generic types don't seem to care about the types of the property values in T at all. If that is true, you'd be better served by making them generic in the keys (e.g., type CustomType <K extends keyof any> = { [P in K]: number }; or more succinctly Record<K, number>. Your function would then be generic in K, where T if needed is replaced by Record<K, any>.
    – jcalz
    May 16, 2018 at 13:40
  • It truly doesn't consider value types in T. But with your first example I get error message Type 'T' does not satisfy the constraint 'string'.
    – crazko
    May 16, 2018 at 15:26
  • Does this make more sense?
    – jcalz
    May 16, 2018 at 15:40
  • This is almost exactly what I want to achieve! But now property names of 'values' depend on property names of config - I'd rather want it to be the opposite - config property names should be dependant on values property names.
    – crazko
    May 16, 2018 at 16:15

1 Answer 1

3

Typescript only check for excess properties if you assign an object literal directly to a variable/parameter of a given type, as documented here. In your case you could type config explicitly, or use an object literal directly as an argument:

const values = [
    {
        foo: 'foo',
        bar: 'bar'
    },
    {
        foo: 'foo',
        bar: 'bar'
    }
];

// We type relative to values, no need for the extra interface
const config: Config<typeof values[number]> = {
    foo: {
        highPriority: true,
        callback: () => []
    },
    // will be an error
    wrong: {
        highPriority: true,
        callback: () => []
    }
};

//Or pass the object literal directly 
const result2 = customFunction(values, {
    foo: {
        highPriority: true,
        callback: () => []
    },
    // error
    wrong: {
        highPriority: true,
        callback: () => []
    }
});

Another option is to use conditional types and an extra parameter to trigger an error if the passed type has extra properties:

type NoExtraProperties<TSource, TTarget> = Exclude<keyof TSource, keyof TTarget> extends never ? true : "Extra properties detected";
const customFunction = <T, TConfig extends Config<T>>(values: T[], config: TConfig, validate: NoExtraProperties<TConfig, T>): Array<CustomType<T>> => {
    // logic...

    return [];
};

// Argument of type 'true' is not assignable to parameter of type '"Extra properties detected"'.
const result = customFunction(values, config, true); 

Playground link

8
  • Thanks for the answer, I didn't know about the difference between passing the variable and object literal directly.
    – crazko
    May 16, 2018 at 15:12
  • Unfortunately I didn't thoroughly specified my current conditions: - config is defined elsewhere and doesn't know about values variable (I import an interface though, that's why I used it in the bottom). So your first option can't work - I use customFunction in several places across the application so passing the config as object literal is not viable. That's why I want to store it in the variable. Regarding your third option - I don't understand how to apply it in my case.
    – crazko
    May 16, 2018 at 15:19
  • @crazko What is tripping you up with the third option ? The config parameter has to be of a generic type argument, and you need an extra parameter that is always be passed as the value true but whose type will change based on whether the types are an exact match or not. If the match is not exact the type will not be true and thus the call will cause an error May 16, 2018 at 15:27
  • Ah, I see now. With that specified it is needed to include all properties of values in config (while I want them to be optional). Additionally, wrong property is still allowed to be in config. ... Or it is also possible I use it incorrectly and need to play with it more.
    – crazko
    May 16, 2018 at 15:37
  • @crazko No the properties can stay optional, just that id config has extra properties, you will get an error. I added a playground link to demonstrate the behavior. The error will not be on the config parameter but rather on the validation parameter May 16, 2018 at 15:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.