92 Matching Annotations
  1. Oct 2023
  2. Sep 2023
  3. Aug 2023
    1. Add aliases to vite.config.ts

      ```js import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import path from 'path';

      // https://vitejs.dev/config/ export default defineConfig({ resolve: { alias: { '@': path.resolve(__dirname, './src'), '@assets': path.resolve(__dirname, './src/assets'), '@components': path.resolve(__dirname, './src/components'), }, }, plugins: [react()] }) ```

      Add aliases to tsconfig.json

      ```js { "compilerOptions": { // ... your other compiler options "baseUrl": ".", "paths": { "@/": ["src/"], "@components/": ["src/components/"], "@assets/": ["src/assets/"] }, }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] } ````

      Use alias

      js import image from `@assets/image.png`

  4. Jul 2023
  5. Jun 2023
  6. May 2023
    1. With TypeScript 3.7, TypeScript added support for generating .d.ts files from JavaScript using JSDoc syntax. This set up means you can own the editor experience of TypeScript-powered editors without porting your project to TypeScript, or having to maintain .d.ts files in your codebase.

      npx -p typescript tsc src/**/*.js --declaration --allowJs --emitDeclarationOnly --outDir types

    1. js /** * This component is just a Box with border. * It serves as an example of how you can incorporate * components together. * * Component also has slots, methods and events. * * @component * @example <caption>Basic usage just with the default slot</caption> * <Box> * I am inside a slot * </Box> * * @example <caption>Using second component inside</caption> * <Box> * <ProgressBar :spent="spent" :remaining="50"></ProgressBar> * </Box> * * @example <caption>Example of passing an entire component in a preview</caption> * { * template: `<Box> * <ProgressBar :spent="spent" :remaining="50"></ProgressBar> * <ProgressBar :spent="50" :remaining="50" style="margin-top: 20px"></ProgressBar> * </Box>`, * data: function() { * return {spent: 223}; * } * } */ export default { name: "Box", props: { /** * This will be in the header */ title: { type: String, default: "My box" } }, methods: { /** * Also, you can describe methods for each component * the same as you would do this in regular @jsdoc * documented file * * @param {string} prop1 some example property * @param {string} prop2 other property */ exampleMethod(prop1, prop2) { // method body // The method could even throw an event /** * This event could be thrown by component in case * of some kind of unexpected behaviour. * * @category API * @event unexpectedEvent */ this.$emit('unexpecteEvent') } } }

    1. ```ts

      /* * Initiates a connection to the selected port. / async function connectToServer(): Promise<void> { hostInput.disabled = true; portInput.disabled = true; connectButton.textContent = 'Connecting...'; connectButton.disabled = true;

      try { socket = new TCPSocket(hostInput.value, parseInt(portInput.value)); connection = await socket.opened; term.writeln('<CONNECTED>'); connectButton.textContent = 'Disconnect'; connectButton.disabled = false; } catch (e) { console.error(e); term.writeln(<ERROR: ${e.message}>); markDisconnected(); return; }

      try { reader = connection?.readable.getReader(); for (;;) { const {value, done} = await reader.read(); if (value) { await new Promise<void>((resolve) => { term.write(value, resolve); }); } if (done) { break; } } reader.releaseLock(); reader = undefined; } catch (e) { console.error(e); term.writeln(<ERROR: ${e.message}>); }

      markDisconnected(); }

      /* * Closes the currently active connection. / async function disconnectFromServer(): Promise<void> { // Canceling |reader| will close the connection and cause the read loop in // connectToServer() to exit when read() returns with done set to true. if (reader) { await reader.cancel(); } } ```

  7. Apr 2023
  8. Mar 2023
    1. Put that TS code in a file your app imports, for example, in remix.env.d.ts, and now the type of name will be the expected one.

      ts declare module "@remix-run/server-runtime" { export interface AppLoadContext { name: string; } }

    1. If we want to create an immutable, read only Tuple in Typescript, we can use the readonly keyword when defining our Tuple.

      ts const myArray:readonly[number, string] = [10, 'test'];

    2. Unlike the tuple type in vanilla Javascript, Typescript Tuples by default are mutable - so they can be changed. As such, we can update a Tuple by simply referring to the element we want to update, and redefining it, assuming it isn't a constant:
      Mutating a Typescript Tuple

      ```ts let myTuple:[ string, number ] = [ "some", 15 ]

      myTuple[1] = 20; ```

    3. We can also define an array of Tuples in Typescript. This is done by adding [] to the end of our Tuple type definition:

      ts let myTuple:[ string, number ][] = [ [ "some", 15 ], [ "other", 20 ], [ "tuple", 50 ] ];

    4. ts const myTuple:[ string, number ] = [ "some", 15 ]

    1. Now we have autocomplete and typechecking.

      ```ts type ColorDSValue = "black100" | "black80" | "blue100" | "red150" // | etc type ColorOtherString = string & {}

      type Color = ColorDSValue | ColorOtherString ```

    2. This is so so useful for types or props where you want the general type for support (string), but you also want the specific type for autocomplete ("black100"). It made my whole week when I figured that out and made that color type.
    3. This weird-looking intersection of string & {} makes it so that the specific strings "hello" and "world" are distinguished from string as a whole type.

      ts const wow: ("hello" | "world") | (string & {}) // `wow` is of type `"hello"` or `"world"` or `string`.


  9. Feb 2023
  10. Jan 2023
  11. Dec 2022
  12. Nov 2022
  13. Aug 2022
    1. The unary plus operator (+) precedes its operand and converts it into a number. If it fails to convert the operand into a number, then it returns NaN. The unary (-) operator converts the operand into a number and negates it.

      an alternative to !!, in order to convert null, empty strings, boolean values into 0 or 1.

  14. May 2022
  15. Apr 2022
  16. Feb 2022
  17. Jan 2022
  18. Dec 2021
    1. The correct way to handle TypeScript functional destructuring is to define an interface and reference the interface after the destructure. TypeScript is then able to understand that the function takes an object argument that is of the shape of the Person interface and destructuring occurs as you would expect it to in ES6.
      // a 'Person' object requires 'first' and 'last' 
      // properties whose values are strings
      interface Person {
        first: string;
        last: string;
      }
      
      // This defines that the first functional argument 
      // must be an Array of 'Person' objects, then destructs
      // the first person's first and last name properties
      const helloFirstPerson = ([{ first, last }]: Person[]) =>
        `Hello ${first} ${last}!`;
      
      const people = [
        { first: 'John', last: 'Doe' },
        { first: 'Jane', last: 'Smith' }
      ];
      
      // outputs "Hello John Doe!"
      helloFirstPerson(people);
      
      /* --------- Example of a Type Error ----------- */
      // This creates an array argument that will be invalid for
      // the helloFirstPerson() function, because there are no 'last'
      // props on the 'people' objects
      const badArgs = [{ first: 'John' }, { first: 'Jane' } ];
      
      // Type Error! 
      // Property 'last' is missing in type '{ first: string; }'
      helloFirstPerson(badArgs);
      
  19. Nov 2021
    1. You'll use a (70%, 20%, 10%) split for the training, validation, and test sets. Note the data is not being randomly shuffled before splitting. This is for two reasons: It ensures that chopping the data into windows of consecutive samples is still possible. It ensures that the validation/test results are more realistic, being evaluated on the data collected after the model was trained.

      Train, Validation, Test: 0.7, 0.2, 0.1

  20. May 2020
    1. const Hello: React.FC<Props> = ({ who }) => (  <p>Hello, {who}</p>);

      最简单的 FC props定义方式

  21. Nov 2019
  22. Oct 2019
  23. Sep 2019
    1. ts-node enables you to execute TypeScript directly, just as you might execute JavaScript code using Node.
  24. Nov 2018
  25. Oct 2018
  26. Sep 2018