Yan Dev

Yan Dev

TypeScript: Declaration merging, Type never usage, Generic object type, Unknown type

TypeScript: Declaration merging, Type never usage, Generic object type, Unknown type

4. Declaration merging, Type never usage, Generic object type, Unknown type

Declaration merging

We can only use this feature with interfaces. And define the props multiple times in different parts of our code. All defined properties can be accessed in one interface.

  interface Products{
        title: string,
        price: number
    }

    interface Products {
        amount: number,
        author: string
    }

    const BookByDoyle: Products = {
        title: 'The adventure of Sherlock Holmes',
        price: 100,
        amount: 50,
        author: 'Arthur Conan Doyle'
    }

Type never usage

I used the getBook function from the previous article. The "Never" type can help when we are working in a large team and we need to create more types for our books. The never type will tell us that we should add a new switch statement and our code will work as expected.

type Book = {
  title: string,
  price: number
}

type ScientificBook = {
    prize: number,
    isbn: 100
} & Book

type RareBook = {
    status: boolean
    isbn: 200
} & Book

type SimpleBook = {
    discount: 10
    isbn: 300
} & Book

 type ComplexBook = ScientificBook | RareBook | SimpleBook

    function getBook(book: ComplexBook){

        switch(book.isbn){
            case 100:
                console.log(book.prize)
                break;
            case 200:
                console.log(book.status)
                break;
            case 300:
                console.log(book.discount)  
                break;      
            default:
                console.log(book) //never type
                const never: never = book;
                return never
        }
    }

Generic object type

In different scenarios, we can use a different way of defining an object as an argument to a function.

    function getInfo(info: {[key: string]: string | number}){
        console.log(info.age)
    }

    getInfo({ age: 23, name: 'Arthur' })

Unknown type

if we don't know about the type of the object's value. We could use an unknown type and check the value in the function and do some operations.

      function getInfo(info: {[key: string]: unknown}){
        if(typeof info.age === 'number'){
             info.age++
        } 
        if(typeof info.name === 'string'){
             info.name = info.name.replace("A", "G")
        }
        return info
    }

    const result = getInfo({ age: 23, name: 'Arthur' })
    console.log(result)
 
Share this