5

I'm trying to do a better typing with mongoose schemas, but it seems that the SchemaTypeOpts interface has a [other: string]: any;, which prevents the vcsode intellisense from helping me.

To solve that i tried the following in the hope that it would identify keys created by the dynamic propriety (since its name is other):

const x: Pick<SchemaTypeOpts<any>, Exclude<keyof SchemaTypeOpts<any>, "other">> = {
    bob: "", // expected an error here
    type: String
}

but it seems Exclude doesn't really do much when the interface has a dynamic property :/

ex: this works:

interface test2 {
    x?: number,
    y?: string,
    z?: number,
}


const x: Pick<test2, Exclude<keyof test2, "z">> = {
    y: "",
    z: 5, // got error here because z is excluded
    bob: "" //got error here because bob is not in the interface
}

this does nothing:

interface test2 {
    x?: number,
    y?: string,
    z?: number,
    [other: string]: any;
}


const x: Pick<test2, Exclude<keyof test2, "z">> = {
    y: "",
    z: 5,
    bob: ""
}

How can i remove the [other: string]: any from the interface without re-declaring the whole thing?

Mateus Amorim
  • 96
  • 1
  • 5
  • Possible duplicate of [How can I remove a wider type from a union type without removing its subtypes in TypeScript?](https://stackoverflow.com/questions/51954558/how-can-i-remove-a-wider-type-from-a-union-type-without-removing-its-subtypes-in) – jcalz Apr 16 '19 at 13:19
  • 1
    The answer in there lets you do `Pick>` to strip off the index signature... or you can do `Pick, "keyToRemove">>`. If you need to add the index signature back into the resulting type you can. – jcalz Apr 16 '19 at 13:21
  • yes, thank you @jcalz it seems that solved my problem :). I didn't understood the entire piece of code for `KnownKeys` (never saw that `infer` berfore and the `?` at the end confused me a bit too), but everything worked out in the end, now i can declare my schemas with intellisense help and place the documentation on the interfaces (and see it on the schema declaration). – Mateus Amorim Apr 16 '19 at 14:38

0 Answers0