Home > Software engineering >  typescript typeof with union or generic
typescript typeof with union or generic

Time:08-20

I'm new with typescript and try to undertsand how to make type from typeof but there is the problem.

Lets say i have const filter

export const filter = {
    filters: {
        name: {value: '' , matchMode: ''}
    }
}

Then i make FilterType from const filter using typeof

type FilterType = typeof filter

Then i create const myFilter which type is FilterType

export const myFilter: FilterType = {
  filters: {name:{value: 'myValue' , // how to make possible to accept number too?
                 matchMode: 'contains'}} // how to limit matchMode to accept only values 'contain' or 'eq'
}

Everithing forks fine if keys value and matchMode is a string but it doesn't work if a pass number for example, or i would like predefine matchMode and access only if value is contain or 'eq'

How could i achieve this? I suppose it could be done with Generic, but how?

CodePudding user response:

You can provide extra types for your properties up front:


type Name = {
  value: string | number
  matchMode: 'contains' | 'eq'
}

const name_: Name = {
  value: 2,
  matchMode: 'contains'
}
const filter = {
  filters: {
    name: name_,
  }
}
type FilterType = typeof filter

const myFilter: FilterType = {
  filters: {
    name: {
      value: 2, // ok
      matchMode: 'not contains' // expected error
    }
  } 
}

CodePudding user response:

Define a type first like this

interface FilterType {
  filters: {
    name: {
      value: string | number;
      matchMode: 'contain'|'eq'
    }
  }
}

And then

export const myFilter: FilterType = {
  filters: {
    name:{
      value: 'myValue', // string or number
      matchMode: 'contains' // string or number
    }
  }
}
  • Related