basarat / typescript-book

:books: The definitive guide to TypeScript and possibly the best TypeScript book :book:. Free and Open Source 🌹
https://basarat.gitbook.io/typescript/
Other
20.77k stars 2.54k forks source link

Change 'extra properties' type from `any` to `unknown` #612

Closed dwjohnston closed 3 years ago

dwjohnston commented 3 years ago

I think this is a much better practice, as it will prevent the developer from doing something like:

function logIfHasName(something: { name?: string, [key: string]: unknown}) {
    if (something.name) {
        console.log(something.name);
        console.log(something.foo.bar); //Object is of type 'unknown'.(2571)
    }
}

As opposed to


function logIfHasName2(something: { name?: string, [key: string]: any}) {
    if (something.name) {
        console.log(something.name);
        console.log(something.foo.bar); //is allowed
    }
}

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAGzgcwJLABIEMDOAcrgLYCmAFPnOVABYxhoBciA3omKWQPyv5QATozQAaRAG0A1mQCe-ISIC6rcFLBwA7mAC+ASnYAoRCcQxgiKjTL0RAOi7kDbY6bcQE1ZGTuo0V2gYmB249AG5XNxMPMC8fPwCbILQ7YDg4OwAjXEFwxAB6fIB5TIArMmgzfEQ4CyhZAAcyRAByNQ1tFrsKACYAVgB2AEY9SMQdQwnDUEhYBBR0LDwibh7E2yZWDkdeBWEmcWk5PeVWXDBZfSM3c0tqQPsd5zH3TzhvX3R15JCnCKjTDE4p9-PckvY0hlsrkwgV8jBqrhkKhNGQACZjCY6IA