KJason
KJason

Reputation: 23

In Typescript: Is there a way to initialize an object or array inline (with a certain interface type)?

In Typescript I want to do something like this:

interface SomeType {
 name: string
}
useState([]:SomeType[]); // This creates an empty array of SomeType inline & calls a function called useState

or even

function getArrayOfSomeType():SomeType[] {
  return []:SomeType[];
}

Other cases might involve the same concept but with a map/dictionary:

// Maybe there is a better way to declare maps?
interface MapOfSomeTypes {
 [key:string]: SomeType
}

function getMapOfTypes():MapOfSomeTypes {
  return {} as MapOfSometypes; // or perhaps {}:MapOfSomeTypes
}

This is to get around having to declare these before and then returning them or passing them to another function when all I need is an empty version of them (like for react-hooks).

Upvotes: 2

Views: 317

Answers (1)

zerkms
zerkms

Reputation: 254944

No need to declare them explicitly - typescript would infer it for you, hence

interface SomeType {
 name: string
}
useState([]);
function getArrayOfSomeType():SomeType[] {
  return [];
}
interface MapOfSomeTypes {
 [key:string]: SomeType
}

function getMapOfTypes():MapOfSomeTypes {
  return {};
}

Upvotes: 2

Related Questions