Home > Software design >  How to declare typescript type as "variable" for repeated use?
How to declare typescript type as "variable" for repeated use?

Time:10-17

I am learning typescript right now and from what I know you can do (This is just a simplified example):

interface IExample1 { 
  Value: String | Number | String[] | Number [] 
}

interface IExample2 { 
  Value: String | Number | String[] | Number [] 
}

Both value's of IExample1 and IExample2 have the same types. Is there a way to somehow declare the type of Value and reuse it when needed?

Would look something like this:

ValueType = String | Number | String[] | Number [] 

interface IExample1 { 
  Value: ValueType
}

interface IExample2 { 
  Value: ValueType
}

For some reason I was unable to find anything related (not sure what to search for)

CodePudding user response:

Try following code

type valueType = String | Number | String[] | Number []

interface IExample1 { 
  Value: valueType
}

interface IExample2 { 
  Value: valueType
}

CodePudding user response:

From the documenation:

Type aliases create a new name for a type. Type aliases are sometimes similar to interfaces, but can name primitives, unions, tuples, and any other types that you’d otherwise have to write by hand.

type ValueType = String | Number | String[] | Number [] 

interface IExample1 { 
  Value: ValueType
}

interface IExample2 { 
  Value: ValueType
}

Playground Link

A new type is not created, just a new name for the type is created.

CodePudding user response:

First of all, I'd willing to bet that for this simple case you don't need to use constructor types like Number or String. You should use stirng and number instead. Please see docs

Number type refers to Number constructor in pure js, whereas number refers to primitive type.

If you want to avoid repetition, you can use distributive-conditional-types:

type ValueType<T> = T extends any ? T | T[] : never

type Value = ValueType<string | number>

interface IExample1 {
    Value: Value
}

interface IExample2 {
    Value: Value
}

Playground

  • Related