352 Matching Annotations
  1. Oct 2023
  2. May 2023
    1. A type-script of 768 pages (labeled simply The Big Typescript) dated from 1933 had been in the estatesince 1951, but only in 1967 were the “Zettel” recognized from which it was compiled.Cut-and-paste was integral: “Usually he continued to work with the typescripts. A methodwhich he often used was to cut up the typed text into fragments (‘Zettel’) and to rearrangethe order of the remarks”.17

      via: Georg Henrik von Wright, “The Wittgenstein Papers,” The Philosophical Review 78:4 (1969), 483–563, here: 487.

      von Wright seems to indicate that Wittgenstein created typescripts which he cut up into zettel and then was able to rearrange them into final forms.

    1. secret

      From LAWLER 233: Stoddart cancelled the following lines in the typescript: "There was love in every line, and in every touch there was passion."

      From "Oscar Wilde's Dorian Gray, Annotated & Uncensored": This sentiment belongs to an established literary convention: the artistic process is being equated with sexual intimacy. Normally, however, the artist is male and his subject (or model) female. Wilde is adding an unmistakably homoerotic twist to this tradition.

    2. But that was all.

      From LAWLER 233: Wilde cancelled "He felt no romance for him" in the typescript.

    3. For a moment he thought of praying that the horrible sympathy that existed between him and the picture might cease. It had changed in answer to a prayer; perhaps in answer to a prayer it might remain unchanged. And, yet, who, that knew anything about Life, would surrender the chance of remaining always young, however fantastic that chance might be, or with what fateful consequences it might be fraught? Besides, was it really under his control? Had it indeed been prayer that had produced the substitution? Might there not be some curious scientific reason for it all? If thought could exercise its influence upon a living organism, might not thought exercise an influence upon dead and inorganic things? Nay, without thought or conscious desire, might not things external to ourselves vibrate in unison with our moods and passions, atom calling to atom, in secret love or strange affinity? But the reason was of no importance. He would never again tempt by a prayer any terrible power. If the picture was to alter, it was to alter. That was all. Why inquire too closely into it?

      From LAWLER 227: This paragraph was added in the typescript.

    4. Her little hands stretched blindly out, and appeared to be seeking for him.

      From LAWLER 215: This sentence was added in the typescript.

    5. "If you want him to marry this girl, tell him that, Basil. He is sure to do it then.

      From LAWLER 206: This was written in the manuscript's margin, and the following sentence was added in the typescript.

    6. I have a distinct remembrance of being married, but I have no recollection at all of being engaged. I am inclined to think that I never was engaged."

      From LAWLER 206: Added in the typescript.

    7. "Except in America.

      From LAWLER 206: Wilde added this in the typescript.

    8. Poor Sibyl! what a romance it had all been! She had often mimicked death on the stage, and at last Death himself had touched her, and brought her with him. How had she played that dreadful scene? Had she cursed him, as she died? No; she had died for love of him, and love would always be a sacrament to him now. She had atoned for everything, by the sacrifice she had made of her life. He would not think any more of what she had made him go through, that horrible night at the theatre. When he thought of her, it would be as a wonderful tragic figure to show Love had been a great reality. A wonderful tragic figure? Tears came to his eyes as he remembered her child-like look and winsome fanciful ways and shy tremulous grace. He wiped them away hastily, and looked again at the picture.

      From LAWLER 226: This paragraph was added in the typescript.

    9. He covered page after page with wild words of sorrow, and wilder words of pain.

      From LAWLER 220: Wilde added this in the typescript.

    10. Three o'clock struck, and four, and half-past four, but he did not stir. He was trying to gather up the scarlet threads of life, and to weave them into a pattern; to find his way through the sanguine labyrinth of passion through which he was wandering. He did not know what to do, or what to think.

      From LAWLER 220: Wilde added these sentences in the typescript.

    11. Or was there some other, more terrible reason? He shuddered, and felt afraid, and, going back to the couch, lay there, gazing at the picture in sickened horror.

      From LAWLER 220: Wilde had added these sentences in the typescript.

    12. A long line of boys carrying crates of striped tulips, and of yellow and red roses, defiled in front of him, threading their way through the huge jade-green piles of vegetables. Under the portico, with its gray sun-bleached pillars, loitered a troop of draggled bareheaded girls, waiting for the auction to be over.

      From LAWLER 216: Added in the typescript.

      ZABROUSKI: After these sentences, Wilde revised the rest of the paragraph in 1891: "Others crowded round the swinging doors of the coffee-house in the piazza. The heavy cart-horses slipped and stamped upon the rough stones, shaking their bells and trappings. Some of the drivers were lying asleep on a pile of sacks. Iris-necked and pink-footed, the pigeons ran about picking up seeds. After a little while, he hailed a hansom and drove home. For a few moments he loitered upon the doorstep, looking round at the silent square, with its blank, close-shuttered windows and its staring blinds. The sky was pure opal now, and the roofs of the houses glistened like silver against it. From some chimney opposite a thin wreath of smoke was rising. It curled, a violet riband, through the nacre-coloured air."

    13. The sky was pure opal now, and the roofs of the houses glistened like silver against it.

      From LAWLER 216: This sentence was also added in the typescript.

    14. apes

      From LAWLER 215: Wilde had originally had these lines in the typescript, but crossed them out before publication: "A man with curious eyes had suddenly peered into his face and then dodged him with stealthily footsteps, passing and repassing him many times." It is likely that Sibyl's avenging brother, James, added in 1891, may have originated here.

    15. I have the greatest contempt for optimism.

      From LAWLER 207: This sentence and the four immediately following were added in the typescript.

    16. and find good qualities in the highwayman in the hope that he may spare our pockets.

      From LAWLER 207: Added in the typescript.

    1. had!

      From LAWLER 277: Following this exclamation, Wilde originally had the following: "I have always been too much of a critic. I have been afraid of things wounding me, and have looked on." He canceled it in the typescript.

    2. The tragedy of old age is not that one is old, but that one is young

      From LAWLER 277: Wilde added this epigram in the typescript.

    3. and always wore a Waterbury watch. Why should he be murdered?

      From LAWLER 276: Wilde added this in the typescript.

    4. But

      From LAWLER 274: Stoddart canceled "her life is not spoiled" here in the typescript.

    5. I

      From LAWLER 274: Stoddart canceled "said to myself, 'I won't ruin this girl. I won't bring her to shame. And I...'" in the typescript.

    6. to her. You remember Sibyl, don't you? How long ago that seems! Well, Hetty

      From LAWLER 274: Wilde added this in the typescript.

    7. Why, they will hang me, Alan! Don't you understand? They will hang me for what I have done."

      From LAWLER 270: Wilde added this in the typescript.

    8. very quietly, but watching the effect of each word upon the face of the man he had sent for,

      From LAWLER 269: Wilde added this in the typescript.

    9. and then got up hastily,

      From LAWLER 266: Here, Wilde canceled the following in the typescript: "and having thrown on his heavy white dressing gown, passed into the bathroom. When he came out again, he felt calmer.

    10. But youth smiles without any reason. It is one of its chiefest charms.

      From LAWLER 265: Added in the typescript.

    11. He walked up and down the room for a quarter of an hour, biting his lip, and thinking.

      From LAWLER 265: Added in the typescript.

    12. except that he would write to you."

      From LAWLER 265: Added in the typescript.

    13. pain

      From LAWLER 263: Wilde changed this from "in the uncertain gloom" in the typescript. In 1891, Wilde changed "as if in pain" to "to and fro."

    14. The room is damp. The mildew has got into the canvas. The paints I used had some wretched mineral poison in them. I tell you the thing is impossible."

      From LAWLER 261: Wilde added this in the typescript margin.

    1. chapter

      From LAWLER 254: Changed by Wilde from "passage" in the typescript. In the next line, Stoddart substituted "the hero" for "Raoul."

    2. chapter

      From LAWLER 254: "Fourth chapter" was cancelled in the typescript. Wilde changed this to "seventh chapter" in 1891.

    3. hero

      From LAWLER 254: Originally "Raoul" in the typescript.

    4. He had a special passion, also, for ecclesiastical vestments, as indeed he had for everything connected with the service of the Church. In the long cedar chests that lined the west gallery of his house he had stored away many rare and beautiful specimens of what is really the raiment of the Bride of Christ, who must wear purple and jewels and fine linen that she may hide the pallid macerated body that is worn by the suffering that she seeks for, and wounded by self-inflicted pain. He had a gorgeous cope of crimson silk and gold-thread damask, figured with a repeating pattern of golden pomegranates set in six-petalled formal blossoms, beyond which on either side was the pineapple device wrought in seed-pearls. The orphreys were divided into panels representing scenes from the life of the Virgin, and the coronation of the Virgin was figured in colored silks upon the hood. This was Italian work of the fifteenth century. Another cope was of green velvet, embroidered with heart-shaped groups of acanthus-leaves, from which spread long-stemmed white blossoms, the details of which were picked out with silver thread and colored crystals. The morse bore a seraph's head in gold-thread raised work. The orphreys were woven in a diaper of red and gold silk, and were starred with medallions of many saints and martyrs, among whom was St. Sebastian. He had chasubles, also, of amber-colored silk, and blue silk and gold brocade, and yellow silk damask and cloth of gold, figured with representations of the Passion and Crucifixion of Christ, and embroidered with lions and peacocks and other emblems; dalmatics of white satin and pink silk damask, decorated with tulips and dolphins and fleurs de lys; altar frontals of crimson velvet and blue linen; and many corporals, chalice-veils, and sudaria. In the mystic offices to which these things were put there was something that quickened his imagination.

      From LAWLER 251: Wilde added this paragraph on two handwritten pages to add to the typescript.

    5. some pearly cell in the brain, or some white nerve in the body,

      From LAWLER 246: Stoddart or another editor at Lippincott's knew anatomy better than Wilde and revised the typescript from Wilde's "ivory cell... or scarlet nerve."

    6. the work of some of the finest artists of

      From LAWLER 241: Wilde added this in the typescript.

    7. full of argot and of archaisms, of technical expressions and of elaborate paraphrases,

      From LAWLER 241: Wilde added this in the typescript.

    8. Or was that only his fancy?

      From LAWLER 235: Wilde added this effect in the typescript, which originally read, "the man bowed and retired."

  3. Apr 2023
    1. 'The Bard.'

      From LAWLER 201: Wilde had substituted this from "Shakespeare."

    2. Faithlessness is to the emotional life what consistency is to the intellectual life,—simply a confession of failure.

      From LAWLER 198: Wilde added this epigram to the typescript and followed it up with four additional sentences in 1891: "Faithfulness! I must analyze it someday. The passion for property is in it. There are many things that we would throw away if we were not afraid that others might pick them up."

    3. I am putting it into practice, as I do everything you say."

      From LAWLER 197: This sentence was added in the typescript.

    4. Nowadays people know the price of everything, and the value of nothing."

      From LAWLER 196: This well-known epigram was added to the typescript.

    5. "Am I really like that?""Yes; you are just like that.""How wonderful, Basil!"

      From LAWLER 194: Wilde added this to the typescript.

    6. "And you know you have been a little silly, Mr. Gray, and that you don't really mind being called a boy.""I should have minded very much this morning, Lord Henry.""Ah! this morning!

      From LAWLER 193: Wilde added these sentences to the typescript.

    7. Oh, if it was only the other way! If the picture could change, and I could be always what I am now! Why did you paint it? It will mock me some day,—mock me horribly!"

      From LAWLER 192: Added by Wilde in the typescript.

    8. When I find that I am growing old, I will kill myself."

      From LAWLER 192: Wilde added this sentence in the typescript.

    9. "How sad it is!" murmured Dorian Gray, with his eyes still fixed upon his own portrait. "How sad it is! I shall grow old, and horrid, and dreadful. But this picture will remain always young. It will never be older than this particular day of June. . . . . If it was only the other way! If it was I who were to be always young, and the picture that were to grow old! For this—for this—I would give everything! Yes, there is nothing in the whole world I would not give!"

      From LAWLER 191: Wilde altered this passage each time he revised his text. After "dreadful," he cancelled the following: "Life will send its lines across my face. Passion will create it and thought twist it from its form." For the typescript of this edition, Wilde added the last sentence of this paragraph. In 1891, Wilde added another sentence at the paragraph's end: "I would give my soul for that."

    10. or when some thought that terrifies us lays sudden siege to the brain and calls on us to yield.

      From LAWLER 198: Wilde added this in the margin of the typescript.

    11. "Stop!" murmured Dorian Gray, "stop! you bewilder me. I don't know what to say. There is some answer to you, but I cannot find it. Don't speak. Let me think, or, rather, let me try not to think."

      From LAWLER 186: Wilde added this sentence and the following five paragraphs to the typescript of this edition in a long marginal note ending with "...of the silence."

      ZABROUSKI: This addition plays into Wilde's interest in aestheticism, especially in regards to music, art, and linguistics.

    1. let fraseLegal = 'Bom dia!';fraseLegal = 9.5;

      O código apresentado irá gerar um erro de compilação, pois a variável "fraseLegal" foi inicializada com uma string ('Bom dia!'), mas depois é atribuído um valor numérico (9.5). Como o TypeScript é uma linguagem de tipagem estática, a tentativa de atribuir um valor de um tipo diferente do tipo original da variável resulta em um erro.

      Ou seja, o TypeScript irá indicar que há um erro de tipo devido à incompatibilidade entre os tipos de dados. É importante ressaltar que, em linguagens de tipagem dinâmica, esse erro só seria detectado em tempo de execução e poderia causar problemas de lógica ou falhas no sistema. Mas em linguagens de tipagem estática, como o TypeScript, esse erro é detectado em tempo de compilação, o que torna o código mais seguro e menos propenso a erros de tipo.

    2. [2, 4, 6]

      Esse código define uma função chamada segredo que recebe um array de números como argumento e retorna um novo array com cada elemento multiplicado por 2.

      A função usa o método map do array para iterar sobre cada elemento do array de entrada e aplicar a multiplicação por 2. O resultado é um novo array com os elementos transformados.

      A linha final console.log(segredo([1,2,3])); chama a função segredo com um array de entrada [1, 2, 3] e imprime o resultado da função no console, que seria o array [2, 4, 6].

  4. Feb 2023
    1. "languageServerExample.trace.server": "verbose"

      This is in the contributes part of the package.json

      json "contributes": { "configuration": { "type": "object", "title": "Example configuration", "properties": { "languageServerExample.maxNumberOfProblems": { "scope": "resource", "type": "number", "default": 100, "description": "Controls the maximum number of problems produced by the server." }, "languageServerExample.trace.server": { "scope": "window", "type": "string", "enum": [ "off", "messages", "verbose" ], "default": "off", "description": "Traces the communication between VS Code and the language server." } } } },

    1. If you want a workaround for the case where you can't just replace key with a string literal, you could write your own user-defined type guard function called hasProp(obj, prop). The implementation would just return prop in obj, but its type signature explicitly says that a true result should cause obj to be narrowed to just those union members with a key of type prop: function hasProp<T extends object, K extends PropertyKey>( obj: T, prop: K ): obj is Extract<T, { [P in K]?: any }> { return prop in obj; } and then in your function, replace key in a with hasProp(a, key): function f3(a: A) { const key = 'b'; if (hasProp(a, key)) { return a[key]; // okay } return 42; }
    1. The variable x initially has the type unknown: the type of all values. The predicate typeof x === "number" extracts dynamic information about the value bound to x, but the type-checker can exploit this information for static reasoning. In the body of the if statement the predicate is assumed to be true; therefore, it must be the case the value bound to x is a number. TypeScript exploits this information and narrows the type of x from unknown to number in the body of if statement.
  5. Dec 2022
    1. Typescript added rich type annotations to Javascript, which opened the door to refactoring and static analysis tools that facilitate development and maintenance of large Javascript projects.
    1. Notice that TypeScript not only knows that pet is a Fish in the if branch; it also knows that in the else branch, you don’t have a Fish, so you must have a Bird.

      Can you provide me with some examples of where type predicates can be helpful? Yes, definitely! Type predicates can be very useful in a variety of situations. Here are a few examples of where you might use a type predicate:

      When working with union types, type predicates can help you narrow the type of a value to one of the types in the union. For example, if you have a variable that can be either a string or a number, you can use a type predicate to check the type of the value and narrow it to either string or number depending on the result of the type check.

      Type predicates can also be useful when working with interfaces that have optional properties. For example, if you have an interface that has a optional name property of type string, you can use a type predicate to check whether the name property is present on a value before trying to access it. This can help you avoid runtime errors when accessing optional properties.

      Type predicates can also be useful when working with arrays and other iterable types. For example, if you have an array of values that can be either numbers or strings, you can use a type predicate to check the type of each element in the array and narrow the type of the array to an array of either number or string elements depending on the result of the type checks.

      Overall, type predicates can be very helpful for improving the type safety of your code and avoiding runtime errors. They are particularly useful when working with union types, optional properties, and iterable types.

  6. Sep 2022
  7. 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.

  8. May 2022
  9. Apr 2022
    1. In order to reflect this in the types I added an Either type to the helpers, because with Union Types only the values that the types have in common are directly accessible. So it would have been necessary to first check the returned type before accessing returned properties.

      What does this mean?

    2. It should be | { fallthrough: true } rather than | { fallthrough: boolean } I think (there's no reason you'd have false)
    1. In the caseof Wittgenstein, he worked with typescripts and would often cut upthe typed text into fragments so he could rearrange the order of theremarks jotted on them (Krapp, 2006: 362; von Wright, 1969).

      Wittgenstein worked with typescripts which he would often cut up into fragments so that he could reorder them for his particular needs. He had an unpublished work titled The Big Typescript of 768 pages which he created in this manner.

      Link this to: - Kevin Marks' media fragments and fragmentions work - blackout poetry - mid 1900s newspaper publishing workflows

  10. Feb 2022
    1. Common questions#

      It may be worth highlighting that if "module" = "commonjs" in tsconfig.json, imports such as import { something } from "module" will be transpiled to const module_1 = require("module"). As a result, something will not be available in the debug console, but module_1.something instead.

      One may change tsconfig.json to include "module" = "es6" and "moduleResolution" = "node", and package.json to include "type" = "module", but in this case imports must include the file extension.

  11. Dec 2021
  12. Nov 2021
    1. export interface TasksListSpecifics { 0: ('parallel' | 'sequential'); } export type TasksList = (string[] & TasksListSpecifics); Or more compact: export type TasksList = (string[] & { 0: ('parallel' | 'sequential'); }); The trick is to add your more specific properties on top of array of string type (Array<string>).
    2. add ! to the end of the var that is being spread. E.g. [{}, ...payload!]
    1. Notice that in the else branch, we don’t need to do anything special - if x wasn’t a string[], then it must have been a string.
    2. Animal & { honey: boolean }
    3. Extending a type via intersections
    4. Type aliases and interfaces are very similar, and in many cases you can choose between them freely. Almost all features of an interface are available in type, the key distinction is that a type cannot be re-opened to add new properties vs an interface which is always extendable.
    1. I suggest renaming this to something like SomeInterfaceAsTypeWrittenByHand. Because one of the reasons for Simplify is so you don't have to write SomeType by hand. Then add the following to show that Simplify<SomeInterface> is the same as SomeInterfaceAsTypeWrittenByHand. declare const a: Simplify<SomeInterface>; expectType<SomeInterfaceAsTypeWrittenByHand>(a); // Interface is assignable to its Simplified type (created with Simplify, and by hand) expectType<Simplify<SomeInterface>>(someInterface); expectType<SomeInterfaceAsTypeWrittenByHand>(someInterface);
    1. const palette: { [key: string]: string } = {...
    2. Regarding mapped types, remember that { [K in T]: U } is a special form - it can't be combined with other properties within the { }. So there's not really a name for the [K in T: U] part because it's just part of the overall "mapped type" syntax { [K in T]: U }
    3. what is the TypeScript Way™ of handling the implicit any that appears due to object literals not having a standard index signature?
    4. fresh (i.e. provably do not have properties we don't know about)
    5. Object literals don't have index signatures. They are assignable to types with index signatures if they have compatible properties and are fresh (i.e. provably do not have properties we don't know about) but never have index signatures implicitly or explicitly.
    6. Which... is confusing because Palette technically does have an index signature Palette is a mapped type, and mapped types don't have index signatures. The fact that both use [ ] is a syntactic coincidence.
    7. type PaletteColors = keyof typeof palette type Palette = { [Color in PaletteColors]: string }
    8. Generate type with the index signature: interface RandomMappingWithIndexSignature { stringProp: string; numberProp: number; [propName: string]: string | number | undefined; }
    9. we have no way to know that the line nameMap[3] = "bob"; isn't somewhere in your program
    1. The other commenters are right about the potential solutions. However, it is actually considered a best practice to move the object with the index signature to a nested property.Said differently: No property in the object with the index signature should depart from how the index signature is typed.
    2. Like others have noted, your function does not conform to index signature. [key: string]: string means "all fields are strings" and on the next line you declare a field with function in it.This can be solved by using union types:type IFoo = { [foo: string]: string } & { fooMethod(fooParam: string): void }
    1. you can define locally parse and it should take precedence over the one in the library: interface JSON { parse(text: string, reviver?: (key: any, value: any) => any): unknown; }
    2. This PR adds a new top type unknown which is the type-safe counterpart of any. Anything is assignable to unknown, but unknown isn't assignable to anything but itself and any without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.
    1. So now the question is, why does Session, an interface, not get implicit index signatures while SessionType, an identically-structured typealias, *does*? Surely, you might again think, the compiler does not simply deny implicit index signatures tointerface` types? Surprisingly enough, this is exactly what happens. See microsoft/TypeScript#15300, specifically this comment: Just to fill people in, this behavior is currently by design. Because interfaces can be augmented by additional declarations but type aliases can't, it's "safer" (heavy quotes on that one) to infer an implicit index signature for type aliases than for interfaces. But we'll consider doing it for interfaces as well if that seems to make sense And there you go. You cannot use a Session in place of a WithAdditionalParams<Session> because it's possible that someone might merge properties that conflict with the index signature at some later date. Whether or not that is a compelling reason is up for rather vigorous debate, as you can see if you read through microsoft/TypeScript#15300.
    2. why is Session not assignable to WithAdditionalParams<Session>? Well, the type WithAdditionalParams<Session> is a subtype of Session with includes a string index signature whose properties are of type unknown. (This is what Record<string, unknown> means.) Since Session does not have an index signature, the compiler does not consider WithAdditionalParams<Session> assignable to Session.
    1. The type-fest package contains only types, meaning they are only used at compile-time and nothing is ever compiled into actual JavaScript code. This package contains functions that are compiled into JavaScript code and used at runtime.
    1. Having actual functions here is a non-goal. This package is for types only, meaning nothing ends up compiled into actual JS code.
    2. An interface can be re-opened. Whereas a type is sealed. So a solution for microsoft/TypeScript#15300 is to map the interface (which can be defined in many places) to a type.
  13. Oct 2021
    1. function applyDefaults(fetchFn: typeof fetch, defaults: Required<Parameters<typeof fetch>[1]>)
    2. In rare cases, the underlying types aren't exposed from the library. What shall we do then? Maybe we could also use the typeof operator here too and combine it with a TypeScript's built-in type Parameters. Parameters becomes useful whenever you want to extract the type of parameters from a function type:
  14. Sep 2021
    1. TypeScript is an extension of JavaScript. You can think of it as JavaScript with a few extra features. These features are largely focused on defining the type and shape of JavaScript objects. It requires that you be declarative about the code you're writing and have an understanding of the values your functions, variables, and objects are expecting.While it requires more code, TypeScript is a fantastic means of catching common JavaScript bugs while in development. And for just that reason, it's worth the extra characters.
    2. As a bonus, you have the option of choosing a particular version of JavaScript to target when compiling, so you can use updated JavaScript features, but still, maintain legacy browser support (if you're into that sort of thing)!
    1. Use this to load modules whose location is specified in the paths section of tsconfig.json when using webpack. This package provides the functionality of the tsconfig-paths package but as a webpack plug-in. Using this plugin means that you should no longer need to add alias entries in your webpack.config.js which correspond to the paths entries in your tsconfig.json. This plugin creates those alias entries for you, so you don't have to!
    1. The declarations you make in the tsconfig.json are re-stated in the webpack.config.js. Who wants to maintain two sets of code where one would do? Not me.
    2. Let's not get over-excited. Actually, we're only part-way there; you can compile this code with the TypeScript compiler.... But is that enough?I bundle my TypeScript with ts-loader and webpack. If I try and use my new exciting import statement above with my build system then disappointment is in my future. webpack will be all like "import whuuuuuuuut?"You see, webpack doesn't know what we told the TypeScript compiler in the tsconfig.json.
  15. Aug 2021
    1. which seems to resolve the issue for me and makes no casts, ensuring that Typescript can keep doing its good job of widening as much as necessary and narrowing as much as possible without me having to claim I know better than the compiler. I'm posting it here since it doesn't seem to have been mentioned anywhere.

      makes no casts, ensuring that Typescript can keep doing its good job of widening as much as necessary and narrowing as much as possible without me having to claim I know better than the compiler.

    2. I think a more natural/appropriate behavior for type signature of includes would be for the literal types to be widened.
    1. This isn't too restrictive, and provides a nice type type guard.
    2. function includes<T, U extends T>(arr: readonly U[], elem: T): elem is U { return arr.includes(elem as any); }
    3. Now consider we want to handle numbers in our known value set: const KNOWN_VALUES = Object.freeze(['a', 'b', 'c', 1, 2, 3]) function isKnownValue(input?: string | number) { return typeof(input) === 'string' && KNOWN_VALUES.includes(input) } Uh oh! This TypeScript compiles without errors, but it's not correct. Where as our original "naive" approach would have worked just fine. Why is that? Where is the breakdown here? It's because TypeScript's type system got in the way of the developer's initial intent. It caused us to change our code from what we intended to what it allowed. It was never the developer's intention to check that input was a string and a known value; the developer simply wanted to check whether input was a known value - but wasn't permitted to do so.
    4. Please read https://stackoverflow.com/questions/41750390/what-does-all-legal-javascript-is-legal-typescript-mean
    5. See #14520 for discussion of upper-bounded generics.
    1. I believe he wants to use the as const feature while still type checking that the structure matches an interface. A workaround I'd use for something like that would be interface ITest { a: number; b: string; } let foo = { a: 5, b: "Hello" } as const;
    1. the tuple() function you need can be succinctly written as: export type Lit = string | number | boolean | undefined | null | void | {}; export const tuple = <T extends Lit[]>(...args: T) => args;
    2. const list = ['a', 'b', 'c'] as const; // TS3.4 syntax type NeededUnionType = typeof list[number]; // 'a'|'b'|'c';
    3. This type of assertion causes the compiler to infer the narrowest type possible for a value, including making everything readonly.

      "infer"?

    4. possible to tell the compiler to infer the type of a tuple of literals as a tuple of literals, instead of as, say, string[], by using the as const syntax.
    5. Or, maybe better, interpret the list as a tuple type: const list: ['a','b','c'] = ['a','b','c']; // tuple
    6. One problem is the literal ['a','b','c'] will be inferred as type string[], so the type system will forget about the specific values.
    7. t's not supposed to work with that, since by the time you do const xs = ['a','b','c'] the compiler has already widened xs to string[] and completely forgotten about the specific values.
    1. function strictIsDog<T extends Dog extends T ? unknown : never>( // like <T super Dog> candidate: Dog | T // if Dog extends T then Dog | T is T ): candidate is Dog { // compiler recognizes that Dog | T can narrow to T return "bark" in candidate; } if (strictIsDog(animal)) {} // okay if (strictIsDog(dog)) {} // okay if (strictIsDog(mixed)) {} // okay if (strictIsDog(cat)) {} // error! // ~~~ <-- Cat is not assignable to Dog
    2. If you really want to prevent people from passing in known Cat instances to isDog() you can fake up a lower-bound type parameter constraint like this:
    3. * Now it's correct within the laws of the type system, but makes zero practical sense, * because there exists no runtime representation of the type `Date & string`. * * The type system doesn't care whether a type can be represented in runtime though.

      new tag?: makes zero practical sense

      makes zero practical sense because there exists no runtime representation of the type

    4. no plans to reduce empty cases to never more aggressively to help developers exclude weird/absurd/accidental cases
    5. As a design decision, TypeScript does not collapse that type to `never` (although it could).
    6. candidate is Dog { // compiler recognizes that Dog | T can narrow to T
    7. that is, a type like {foo: never} does not itself get reduced to never even though you shouldn't be able to have a value of type {foo: never}
    8. Using the second type guard forces the user to write a more precise type and therefore manifest any nonsensical type guards that produce never, like: function silly<T extends number>(candidate: T): candidate is T & boolean { … }
    9. You can't just move 'side-ways' between unrelated types; you need to move either up or down the lattice.
    1. function isKeyOfMcuParams(x: string): x is keyof McuParams { switch (x) { case 'foo': case 'bar': case 'baz': return true; default: return false; } }
    2. Is it possible to write a user defined type guard for a keyof string type such as keyOf foo when foo is defined ONLY as a type (and not in an array)?
    1. Introduced in the perfectly named “Typescript and validations at runtime boundaries” article @lorefnon, io-ts is an active library that aim to solve the same problem as Spicery:TypeScript compatible runtime type system for IO decoding/encoding

      io-ts

    2. [K in keyof User]-?:
    3. It means that when having a type guard:TypeScript and JavaScript runtime are tied to the same behaviour.
    4. Inside the if statement, TypeScript will assume that amount cannot be anything else than a string, which is true also at the runtime thanks to typeof JavaScript operator.
    5. This “gap” between what we call “runtime” and “static analysis” can be filled using TypeScript Type Guards.
    6. We will see that this is not a fatality, because TypeScript is more powerful than you thought and some developers of the community are very crafty.
    1. we use a type guard here to say that, if this function returns true, any further usage of key will be of the specified type. Otherwise, it's still just a string.
    2. keyof is a keyword in TypeScript which accepts a given object type and returns a union type of its keys. These are equivalent: type StatusKey = keyof { online: string; offline: string; busy: string; dnd: string; } type StatusKey = 'online' | 'offline' | 'busy' | 'dnd'
    3. function hasKey<O>(obj: O, key: PropertyKey): key is keyof O { return key in obj }
    1. Adding to the accepted answer, if you happen to need to use a type guard against a mixin, you'll get this error too, since the is operator doesn't behave as an implements would.
    2. Regarding the error message, the predicate type must be assignable to the value type because the type guard is used to check whether a value with a less-specific type is in fact a value with a more-specific type. For example, consider this guard: function isApe(value: Animal): value is Ape { return /* ... */ } Ape is assignable to Animal, but not vice versa.
    3. If you really don't want to use any, you could use an empty interface - {} - instead:
    4. If there is no relationship between the value's type and the type in the type predicate, the guard would make no sense. For example, TypeScript won't allow a user-defined guard like this: function isString(value: Date): value is string { return typeof value === "string"; }
    5. the generic means "give me one of each function a -> Boolean" so if any of those functions doesn't exist, then the generic doesn't exist.
  16. Jul 2021
    1. In 2.8 you can use conditional types to achieve a similar effect
    2. type CReturn<C, K extends keyof C> = C extends Array<any> ? C[number] : C[K];
    3. Prior to 2.9 keyof only returned string indexes, in 2.9 this will include numeric and symbol keys.
    4. const test = new Person(TestPerson).at("name").at("name")
  17. Jun 2021
  18. 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.
  19. May 2021
  20. 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?

      Interessante..

  21. 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,
  22. 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.