U
U
Umid2017-02-26 13:12:44
JavaScript
Umid, 2017-02-26 13:12:44

Why is it necessary to specify the type a second time?

interface SquareConfig {
    color?: string;
    width?: number;
}
 
function createSquare(config: SquareConfig): { color: string; area: number } {
    let newSquare = {color: "white", area: 100};
    if (config.color) {
        // Ошибка: Property 'collor' does not exist on type 'SquareConfig'
        newSquare.color = config.color;
    }
    if (config.width) {
        newSquare.area = config.width * config.width;
    }
    return newSquare;
}
 
let mySquare = createSquare({ color: "black" });
console.log(mySquare)

This line is of interest:
function createSquare(config: SquareConfig): { color: string; area: number } {

Or rather, what is written after the colon.
What does it give us?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Interface, 2017-02-26
@DarCKoder

What comes after the colon is the return type of the function. https://www.typescriptlang.org/docs/handbook/funct... I didn't really understand about the second time - the first one is the argument or return newSquare;. TS (modern at least) itself will determine the type by such a return. Those. the part after the colon is optional, but adds clarity
P. s. this will also help avoid an error when trying to make an invalid return inside a function

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question