From 5ef7ab32dfc2a6bcd9ad810e4a3ec3a3961bcf7e Mon Sep 17 00:00:00 2001 From: RMidhunSuresh Date: Fri, 10 Dec 2021 12:09:18 +0530 Subject: [PATCH] Update doc --- doc/TS-MIGRATION.md | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/doc/TS-MIGRATION.md b/doc/TS-MIGRATION.md index a7342ba8..78a4c9ba 100644 --- a/doc/TS-MIGRATION.md +++ b/doc/TS-MIGRATION.md @@ -8,6 +8,30 @@ Good examples of data are option objects to have named parameters, and POJO (pla Also see [this playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBACghgJwgO2AeTMAlge2QZygF4oBvAKCiqmTgFsIAuKfYBLZAcwG5LqATCABs4IAPzNkAVzoAjCAl4BfcuVCQoAYQAWWIfwzY8hEvCSpDuAlABkZPlQDGOITgTNW7LstWOR+QjMUYHtqKGcCNilHYDcAChxMK3xmIIsk4wBKewcoFRVyPzgArV19KAgAD2AUfkDEYNDqCM9o2IQEjIJmHT0DLvxsijCw-ClIDsSjAkzeEebjEIYAuE5oEgADABJSKeSAOloGJSgsQh29433nVwQlDbnqfKA) -## Use `Record` to describe a type that accepts any Javascript object. +## Use `type foo = { [key: string]: any }` for types that you intend to fill in later. -`Record` allows us to avoid passing in primitive types and prevents type errors when accessing properties. As this is a temporary type while converting javascript, it seems best to not add any additional requirements. If any errors occur, they must have already been present, and we should fix it by adding proper types. So prefer `Record` over `[key: string]: any`, `any` or `object`. +For instance, if you have a method such as: +```js + function load(options) { + // ... + } +``` +and you intend to type options at some later point, do: +```ts + type Options = { [key: string]: any} +``` +This makes it much easier to add the necessary type information at a later time. + +## Use `object` or `Record` to describe a type that accepts any javascript object. + +Sometimes a function or method may genuinely need to accept any object; eg: +```js +function encodeBody(body) { + // ... +} +``` +In this scenario: +- Use `object` if you know that you will not access any property +- Use `Record` if you need to access some property + +Both usages prevent the type from accepting primitives (eg: string, boolean...). If using `Record`, ensure you have guards to check that the properties really do exist.