Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

2d object whose key is the same as the keys of a value in the same object

$
0
0

I'm still a newbie in typescript and been searching in google about this for almost 2 hours now.

I want to create a type that is an object that will contain multiple values. The key of one value in the object would be the same as the keys of another value in that same object, except this time they will be functions.

Example value of this would be:

{  values: {    email: '',    password: ''  },  validators: {    email: () => { /* some function that does something and returns a string */ },    password: () => { /* some function that does something and returns a string */ },  }};

In the example above, you see that the keys of validators are the same as the keys of values, except validators are composed of functions.

I can do:

export type Options = {  values: Record<string, unknown>,  validators: Record<string, unknown>};

but this is not robust because I want the autocomplete to happen, I want validators to be a record which keys are the same as the keys of values, except all those are optional and should be functions.

I'm thinking of using generics, but I don't know what to pass to it

type FormValidator<T> = {  [P in keyof T]?: (values: Record<string, unknown>) => string;};export type FormOptions = {  values: Record<string, unknown>;  validators?: FormValidator<this.values>; // WHAT DO I PASS HERE SO THAT IT WILL GET THE KEYS OF VALUES?};

EDIT 1:

One thing that I think works the same as I want this to work is this: enter image description here

https://www.typescriptlang.org/play?#code/C4TwDgpgBAYg9gJwLYDUCGAbAlgEzcRAHgBUA+KAXigG8BYAKCigG0AFKLAOygGsIQ4AMyjEAugC4oACgCUlcgGdgCLgHMA3AwC+m+gwDGcTkqgA3TAFcICyjQZMmEJGiwZJAcncAaew7BoFBQB3RBwPd21dAyMTc2w8AgQbSXhkdHj8IlBIITNLa3IqOkYHSKA

Notice how the autocomplete works, and if you add something else that's not in values, it will also throw an errorenter image description here that's basically how I want it but I want it defined in that one type: type FormOptions

EDIT 2:

I'm wanting to do this in ReactJS / ReactNative and just plain NodeJS/TypeScript (that is, without using any frameworks)


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>