160 Matching Annotations
  1. Last 7 days
  2. Oct 2020
    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.
  3. 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; }; }
  4. 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

  5. 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的风格。

  6. 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推断类型,但是结果类型不大好用。

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

  8. Jan 2020
  9. Dec 2019
  10. 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.
  11. 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. Type Guards
    7. Union Types
    8. Here’s a simple example that shows how to create a mixin:
    9. With index types, you can get the compiler to check code that uses dynamic property names.
    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.
  12. 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.
  13. Aug 2019