DEV Community

Discussion on: 4 Ideas of how to harness the power of Typescript generic function

 
glebirovich profile image
Gleb Irovich

I am not sure if I got the question. But I will try to give a better example.
Let's say you have a generic interface:

interface Item<T> {
  value: T;
}

const item1: Item<string> = { value: "Gleb" }

interface Person {
  name: string;
  age: number;
}

const item2: Item<Person> = { value: { name: "Gleb", age: 27 } }

const item3: Item = {} // Error: Generic type 'Item<T>' requires 1 type argument(s)

If you set a default value of the generic type, item3 will not cause an error. It will set the type of value to any.
You can use any type as a default:

interface Item<T = number> {
  value: T; // Will be number, if no other type is passed to the interface
}

const item: Item = { value: 1 }

Does it answer your question?

Thread Thread
 
jwp profile image
John Peters

Yes I think I saw no value in this:

interface Item<T = any> {

}