The explanation of this in the Chinese net function section of typescript

let deck = {
    suits: ["hearts", "spades", "clubs", "diamonds"],
    cards: Array(52),
    createCardPicker: function() {
        // NOTE: the line below is now an arrow function, allowing us to capture "this" right here
        return () => {
            let pickedCard = Math.floor(Math.random() * 52);
            let pickedSuit = Math.floor(pickedCard / 13);

            return {suit: this.suits[pickedSuit], card: pickedCard % 13};
        }
    }
}

let cardPicker = deck.createCardPicker();
let pickedCard = cardPicker();

alert("card: " + pickedCard.card + " of " + pickedCard.suit);

the tutorial says that the type of this and this.suits [pickedSuit] is any, will report an error. Then a solution is provided

function f(this: void) {
    // make sure `this` is unusable in this standalone function
}

the tutorial says that the this parameter here is a false parameter, how to understand why defining the type of this as void will not report an error?

Feb.14,2022

is just an assertion, that is, the developer asserts that the this in the current scope points to a certain type, and if you don't declare it, it must be the any type.

for your second question, why does it not report an error if it is set to void, as long as you do not use this in the function? if you use this, code such as this.a will report an error.

Menu