352 Matching Annotations
  1. Sep 2020
    1. My solution idea is just to let the compiler knows that rest is of type T, using a custom type guard function, but you could use other approaches, like a type casting: <Child {...((rest as unknown) as T)} />
    1. You can derive the TypeScript type as follows: type Person = yup.InferType<typeof personSchema>;
    1. Let's say you import { Interface } from "api/interfaces", from source file /src/views/View.ts. Typescript would then look for the module in the following paths: /src/views/api/interfaces.ts /src/api/interfaces.ts /api/interfaces.ts
    1. Extend ActionConfig interface in rfc-extended.d.ts file with new params: import * as RFC from 'react-fetching-library'; declare module 'react-fetching-library' { export interface ActionConfig { // Only new params skipAuth: boolean; params: any; }; }
  2. May 2020
    1. TypeScript will see that the a property of A & B is incompatible with that of C: Type 'A & B' is not assignable to type 'C'. Types of property 'a' are incompatible. Type 'number' is not assignable to type 'boolean | undefined'.
    2. In TypeScript 3.9, so long as every type in an intersection is a concrete object type, the type system will consider all of the properties at once.
    1. This starter takes advantage of Typescript and Emotion. This is a personal choice, and I'd encourage you to give it a shot. If you're interested in using plain ES6 and regular scss styling, see release v1 of this library.
    1. All valid JavaScript code is also TypeScript code. You might get type-checking errors, but that won't stop you from running the resulting JavaScript.
    1. Now, a couple of years later, my guidelines for JS are:

      Advices on using JavaScript from a long time programmer:

      1. Use TypeScript instead.
      2. Push as much logic to the server as possible
      3. Use a framework like Vue or React if you need front interactivity
      4. Don't skip unit tests
    1. less easy when you switch from JavaScript to TypeScript. Running TypeScript on Cloud Functions requires a compilation phase to convert the TypeScript into JavaScript so that it can be executed by the emulator. It adds a bit of a hassle

      a bit of a hassle to compile code that can be executed by the emulator

  3. Apr 2020
    1. I found that the overhead to use types in TypeScript is minimal (if any).

      In TypeScript, unlike in JS we need to specify the types:

    2. I need to specify types of input and output. But then I get speedup due to autocompletion, hints, and linting if for any reason I make a mistake.

      In TypeScript, you spend a bit more time in the variable definition, but then autocompletion, hints, and linting will reward you. It also boosts code readability

    3. TSDoc is a way of writing TypeScript comments where they’re linked to a particular function, class or method (like Python docstrings).

      TSDoc <--- TypeScript comment syntax. You can create documentation with TypeDoc

    4. ESLint does automatic code linting

      ESLint <--- pluggable JS linter:

      • mark things that are incorrect,
      • mark things that are unnecessary or risky (e.g. if (x = 5) { ... })
      • set a standard way of writing code
    5. Write a new test and the result. If you want to make it REPL-like, instead of writing console.log(x.toString()) use expect(x.toString()).toBe('') and you will directly get the result.

      jest <--- interactive JavaScript (TypeScript and others too) testing framework. You can use it as a VS Code extension.

      Basically, instead of console.log(x.toString()), you can use except(x.toString()).toBe(''). Check this gif to understand it further

    6. I recommend Airbnb style JavaScript style guide and Airbnb TypeScript)

      Recommended style guides from Airbnb for:

    1. In the above code, we:state, that the FunctionType extends  (args: any) => anywe say that the FunctionReturnType is a conditional typeinside we declare the ReturnType and assign it with the return type of our function () => infer ReturnType results in assigning the return type to the ReturnType variablewe check if FunctionType extends  (...args: any) => infer ReturnTypeif the above condition is not met, we assign  any to FunctionReturnTypesince the above condition is always met, we assign the ReturnType to the FunctionReturnTypeBy doing all of the above, we can extract the return type of any function.

      解释infer及相关情况。

    2. Introducing the infer keyword

      介绍 infer关键字,待细究

    1. The most commonly used type parameter names are:E – Element (used extensively by the Java Collections Framework)K – KeyN – NumberT – TypeV – ValueS,U,V etc. – 2nd, 3rd, 4th types

      常见的泛型类型命名

    2. we can put a constraint on the T type variable.

      添加泛型约束

    1. From TypeScript 3.7 and onwards, you can use optional chaining to simplify working with nullable types.

      从TypeScript3.7开始,可以使用可选链

    1. Within the extends clause of a conditional type, it is now possible to have infer declarations that introduce a type variable to be inferred. Such inferred type variables may be referenced in the true branch of the conditional type. It is possible to have multiple infer locations for the same type variable.

      使用infer

    1. An ambient declaration introduces a variable into a TypeScriptscope, but has zero impact on the emitted JavaScript program.

      环境Declare将变量引入到TypeScript,不会生成JS代码。用它告诉TypeScript编译器其它组件会提供一个变量。

    Tags

    Annotators

    1. For example, noImplicitAny is a recommended option that triggers the compiler to error on expressions and declarations with an implied any type

      开启类型检查

    1. The current answers and the official documentation are outdated. And for those new to TypeScript, the terminology used isn't clear without examples. Below is a list of up-to-date differences.

      关于接口和类型别名,更新的内容

    2. Both can be extended, but again, the syntax differs. Additionally, note that an interface and type alias are not mutually exclusive. An interface can extend a type alias, and vice versa

      接口和类型别名并不互斥,还可以相互扩展。

    1. Any JavaScript style guide that is up-to-date for ES6 is going to cover nearly all TypeScript constructs except for type annotations, so I would start with your favorite JS style and decide on what you want the rules for type annotations to be

      可惜这个问题被关了。因此显得有点老。不过他的建议也不错。使用用JS的风格。

  4. Mar 2020
    1. “undefined as a value” and “undefined as a type” are both written as undefined. Depending on where you use it, it is interpreted as a value or as a type. The same is true for null.

      Depending on location, undefined is interpreted as a value or as a type.

    1. TS 采用结构子类型。其含义是:两个类型,即使表示的业务含义大相径庭,只要结构上有从属关系,就是兼容的。(“等同”也是从属关系的一种)

      TS用结构子类型。不同于C#的名义子类型。

    1. Newer versions of TypeScript can now infer types based on your React.PropTypes (PropTypes.InferProps), but the resulting types can be difficult to use or refer to elsewhere in your code.

      新版TS能通过PropTypes推断类型,但是结果类型不大好用。

  5. Feb 2020
    1. Confusingly, the colon here does not indicate the type. The type, if you specify it, still needs to be written after the entire destructuring:

      Destructuring an object in TypeScript with Types is very counterintituive.

  6. Jan 2020
  7. Dec 2019
  8. Nov 2019
    1. To make your developer experience better I recommend to run type-checking in a separate process by starting TSC compiler (preferably in watch mode) in you terminal with --noEmit and --project flags.
  9. Oct 2019
    1. export function A(param: string): void export function A(param: { param: string, otherProp?: string }): void export function A(paramOrObj: string | { param: string, otherProp?: string } = { param: "initial"}): void {
    1. These are called default-initialized parameters.
    2. In TypeScript, we can also set a value that a parameter will be assigned if the user does not provide one, or if the user passes undefined in its place.
    3. buildName(undefined, "Adams")
    4. If a default-initialized parameter comes before a required parameter, users need to explicitly pass undefined to get the default initialized value.
    5. Exclude<string | number | (() => void), Function>
    6. type ReturnType<T extends AnyFunction> = T extends (...args: any[]) => infer R ? R : any;
    7. type Unpacked<T>
    8. infer declarations that introduce a type variable to be inferred
    9. These typeof type guards are recognized in two different forms: typeof v === "typename" and typeof v !== "typename", where "typename" must be "number", "string", "boolean", or "symbol". While TypeScript won’t stop you from comparing to other strings, the language won’t recognize those expressions as type guards.
    10. Using Type Parameters in Generic Constraints
    11. Type Guards
    12. Union Types
    13. Here’s a simple example that shows how to create a mixin:
    14. With index types, you can get the compiler to check code that uses dynamic property names.
    1. type KeysOfType<A extends object, B extends { [key: string]: any }> = { [K in keyof A]: A[K] extends B ? string extends keyof A[K] ? K : never : never; }[keyof A];
    2. type A = string extends keyof Person["favouriteNumbers"] ? true : false; // true
    3. type A = keyof Person["favouriteNumbers"]; // string | number type B = keyof Person["address"]; // "street" | "postcode"
    4. type KeysOfType<A extends object, B> = { [K in keyof A]-?: A[K] extends B ? K : never; }[keyof A];
    1. Let's make the example even easier. function convertDate<T extends string | undefined>(isoDate?: string): T { return undefined } 'undefined' is assignable to the constraint of type 'T' Means: What you return in the function (undefined), matches the constraints of your generic type parameter T (extends string | undefined). , but 'T' could be instantiated with a different subtype of constraint 'string | undefined'. Means: TypeScript does not consider that as safe. What if you defined your function like this at compile time: // expects string return type according to generics // but you return undefined in function body const res = convertDate<string>("2019-08-16T16:48:33Z") Then according to your signature, you expect the return type to be string. But at runtime that is not the case! This discrepancy that T can be instantiated with a different subtype (here string) than you return in the function (undefined) is expressed with the TypeScript error.
    1. async function createRequest( url: URL | string, { az, queries, ...parameters }: Params & { az: "text" } ): Promise<string>; async function createRequest<R>( url: URL | string, { az, queries, ...parameters }: Params & { az?: "json" } ): Promise<R>; async function createRequest<R>( url: URL | string, { az, queries, ...parameters }: Params ): Promise<R | string> {
    1. In the body of the function you have no control over the instantiation by the calling context, so we have to treat things of type T as opaque boxes and say you can't assign to it. A common mistake or misunderstanding was to constraint a type parameter and then assign to its constraint, for example: function f<T extends boolean>(x: T) { x = true; } f<false>(false); This is still incorrect because the constraint only restricts the upper bound, it does not tell you how precise T may really be.
    1. const renderMapping: { [l in letters]: renderFunction<l>; } = { 'a': (a: 'a') => 'alpha', 'b': (b: 'b') => 'bravo', }; type renderFunction<l extends letters> = (letter: l) => string; function renderLetter<l extends letters>(letter: l): renderFunction<l> { return renderMapping[letter]; }
    1. type Type = 'a' | 'b'; type AShape = { a: 'a' }; type BShape = { b: 'b' }; type Props<T extends Type> = { type: T, shape: T extends 'a' ? AShape : BShape, }; class Test<T extends ID> extends React.Component<Props<T>> { render() { const { type, shape } = this.props; switch (type) { case 'a': return <>{shape.a}</>; // Ideally would narrow `shape` here, instead of `AShape | BShape` default: return <>{shape.b}</>; } } } <T type="a" shape={{ a: 'a' }} /> // No error in ideal case <T type="a" shape={{ b: 'b' }} /> // error in ideal case
    2. type NumberType = (() => number) | number; function double<T extends NumberType>( num: T ) : T { if (typeof num === "number") return num * 2; return () => num() * 2; }
    1. Index types are really handy when you have an object that could have unknown keys. They're also handy when using an object as a dictionary or associative array. They do have some downsides, though. You can't specify what keys can be used, and the syntax is also a bit verbose, in my opinion. TypeScript provides a solution, however; the Record utility.
    1. Project is written in TypeScript and provides type safety out of the box. No Flow Type support is planned at this moment, but feel free to contribute.
  10. Sep 2019
    1. --p or ``--projectand notconfig`. it takes the path the the folder containing tsconfig.json, and starting with 1.8, it will allow a full path to the file
    1. Since TypeScript 1.4 static extensions can be added easily. The TypeScript team changed the lib.d.ts file to use interfaces for all static type definitions. The static type definitions are all named like [Type]Constructor: So if you want to add a static function to type Object, then add your definition to ObjectConstructor.
  11. Aug 2019
  12. Jul 2018
    1. This chapter is about “Basic JavaScript,”

      The highlighted annotations with the airbnb tag were made to illustrate where Basic Javascript differs from the Airbnb Javascript Style Guide and typescript tag for differences from Typescript Deep Dive TIPs.

    2. Or, forEach has a second parameter that allows you to provide a value for this:logHiToFriends: function () { 'use strict'; this.friends.forEach(function (friend) { console.log(this.name+' says hi to '+friend); }, this); }

      Harmful for the same reason as: Bind is Harmful

    3. use the method bind() that all functions have. It creates a new function whose this always has the given value:> var func2 = jane.describe.bind(jane); > func2() 'Person named Jane'
  13. Jul 2017
  14. Oct 2016
    1. April of ‘84

      Rigby's Romance evolved from the fifth chapter of the 1898 typescript version of Such is Life. In that text, the date of Tom Collins' arrival in Echuca is 9 January 1884. Although missing from TS, the date of the record is confirmed by internal evidence, such as Tom Collins’ two arrivals at Deniliquin in the closing pages; ‘2.45, p.m., on a cold winter day, nearly five months after the date of the events just recorded – or, to be precise, on the 3rd of June’ (TS 521); or ‘three o’clock on a Saturday afternoon, six or eight weeks after the date of the events just recorded’ (RR 249).

  15. Jun 2016
    1. @Component

      If using emacs tide-mode, customize variable tide-tsserver-process-environment to include --experimentalDecorators.

  16. Mar 2016
  17. Sep 2015
  18. Aug 2015
    1. In summary:

      1. Class decorators are functions that wrap a constructor function
      2. Property decorators are functions that take a prototype and property name as input and can modify the property
      3. Method decorators are functions that take a prototype, method name and method descriptor as input and return an updated descriptor
    2. let’s implement the logClass decorator..

      This can be simplified slightly to:

      function log(constructor: any) {
          let wrappedConstructor = (...args: any[]) => {
              console.log('creating a new ' + constructor.name, 'with args', JSON.stringify(args));
              let instance: any = Object.create(constructor.prototype);
              constructor.apply(instance, args);
              return instance;
          };
          wrappedConstructor.prototype = constructor.prototype;
          return wrappedConstructor as any;
      }
      
  19. Feb 2015