185 Matching Annotations
  1. Jun 2021
  2. basarat.gitbook.io basarat.gitbook.io
    1. Having a member in a class and initializing it like below:class Foo { x: number; constructor(x:number) { this.x = x; }}is such a common pattern that TypeScript provides a shorthand where you can prefix the member with an access modifier and it is automatically declared on the class and copied from the constructor. So the previous example can be re-written as (notice public x:number):class Foo { constructor(public x:number) { }}
    1. Almost the same applies to typescript and babel-ts. babel-ts might support JavaScript features (proposals) not yet supported by TypeScript, but it’s less permissive when it comes to invalid code and less battle-tested than the typescript parser.
  3. May 2021
  4. Jan 2021
    1. Just use import type {AnimType}... instead

      Solves error for me:

      export 'InterfaceName' was not found in
    2. Basically the typescript compiler emits no code for interfaces, so webpack can not find them in the compiled module; except when a module consists of only interfaces. In that case the module will end up completely empty and then webpack will not investigate the exports.
    1. { item1: "hello", item2: "world" }

      Valida in automatico l'oggetto passato con l'interfaccia?

      Non necessità di un'istanza o di specificare l'interfaccia dell'istanza?


  5. Nov 2020
    1. // DO NOT INLINE this variable. For backward compatibility, foundations take a Partial<MDCFooAdapter>. // To ensure we don't accidentally omit any methods, we need a separate, strongly typed adapter variable.

      I wish I understood what they meant and why this is necessary

    1. Since Typescript 3.0 this can be done with Project References.
    2. The typescript compiler will not look at the actual typescript files from lib. Instead it will only use the typescript declaration files (*.d.ts) generated when building the lib project. That's why your lib/tsconfig.json file must contain: "declaration": true,
  6. Oct 2020
    1. Emulating TypeScript functions

      YEah, but you've also got to watch the source files to recomp0ile on changes....

      "serve": "tsc -w | firebase emulators:start --only functions",

      Modified and functionally watching my stuff

    1. TypeScript provides you with the ability to use something other than React with JSX in a type safe manner.
    1. And yes, template tags cannot have TS right now.
    2. I could imagine people putting a more complex expression in an @const than we typically find in svelte expressions today, which might create more demand for those blocks to have TypeScript support, which I don't think they have now.
    1. This library is built in TypeScript, and for TypeScript users it offers an additional benefit: one no longer needs to declare action types. The example above, if we were to write it in TypeScript with useReducer, would require the declaration of an Action type: type Action = | { type: 'reset' } | { type: 'increment' } | { type: 'decrement' }; With useMethods the "actions" are implicitly derived from your methods, so you don't need to maintain this extra type artifact.
  7. 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; }; }
  8. 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

  9. 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.


    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.


    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.


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




    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


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


    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.


  11. 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.

  12. Jan 2020
  13. Dec 2019
  14. 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.
  15. 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. 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. Exclude<string | number | (() => void), Function>
    2. type ReturnType<T extends AnyFunction> = T extends (...args: any[]) => infer R ? R : any;
    3. type Unpacked<T>
    4. infer declarations that introduce a type variable to be inferred
    5. 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.
    6. Using Type Parameters in Generic Constraints
    7. Type Guards
    8. Union Types
    9. Here’s a simple example that shows how to create a mixin:
    10. With index types, you can get the compiler to check code that uses dynamic property names.