- May 2024
-
www.showbiz411.com www.showbiz411.com
-
Woody Allen Has Used the Same Typewriter for 50 Years! by [[Roger Friedman]] in Showbiz411
Referenced documentary is from PBS: American Masters Woody Allen: A Documentary (2011)
-
-
www.youtube.com www.youtube.com
-
He wrote everything with his Olympia SM3 typewriter. He lost the hood "30 years ago".
He literally cuts and staples pieces of typescripts together.
-
- Oct 2023
-
world.hey.com world.hey.com
- May 2023
-
-
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.
-
-
sites.google.com sites.google.com
-
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.
-
But that was all.
From LAWLER 233: Wilde cancelled "He felt no romance for him" in the typescript.
-
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.
-
Her little hands stretched blindly out, and appeared to be seeking for him.
From LAWLER 215: This sentence was added in the typescript.
-
"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.
-
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.
-
"Except in America.
From LAWLER 206: Wilde added this in the typescript.
-
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.
-
He covered page after page with wild words of sorrow, and wilder words of pain.
From LAWLER 220: Wilde added this in the typescript.
-
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.
-
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.
-
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."
-
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.
-
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.
-
I have the greatest contempt for optimism.
From LAWLER 207: This sentence and the four immediately following were added in the typescript.
-
and find good qualities in the highwayman in the hope that he may spare our pockets.
From LAWLER 207: Added in the typescript.
-
-
sites.google.com sites.google.com
-
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.
-
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.
-
and always wore a Waterbury watch. Why should he be murdered?
From LAWLER 276: Wilde added this in the typescript.
-
But
From LAWLER 274: Stoddart canceled "her life is not spoiled" here in the typescript.
-
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.
-
to her. You remember Sibyl, don't you? How long ago that seems! Well, Hetty
From LAWLER 274: Wilde added this in the typescript.
-
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.
-
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.
-
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.
-
But youth smiles without any reason. It is one of its chiefest charms.
From LAWLER 265: Added in the typescript.
-
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.
-
except that he would write to you."
From LAWLER 265: Added in the typescript.
-
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."
-
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.
-
-
sites.google.com sites.google.com
-
chapter
From LAWLER 254: Changed by Wilde from "passage" in the typescript. In the next line, Stoddart substituted "the hero" for "Raoul."
-
chapter
From LAWLER 254: "Fourth chapter" was cancelled in the typescript. Wilde changed this to "seventh chapter" in 1891.
-
hero
From LAWLER 254: Originally "Raoul" in the typescript.
-
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.
-
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."
-
the work of some of the finest artists of
From LAWLER 241: Wilde added this in the typescript.
-
full of argot and of archaisms, of technical expressions and of elaborate paraphrases,
From LAWLER 241: Wilde added this in the typescript.
-
Or was that only his fancy?
From LAWLER 235: Wilde added this effect in the typescript, which originally read, "the man bowed and retired."
-
- Apr 2023
-
sites.google.com sites.google.com
-
'The Bard.'
From LAWLER 201: Wilde had substituted this from "Shakespeare."
-
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."
-
I am putting it into practice, as I do everything you say."
From LAWLER 197: This sentence was added in the typescript.
-
Nowadays people know the price of everything, and the value of nothing."
From LAWLER 196: This well-known epigram was added to the typescript.
-
"Am I really like that?""Yes; you are just like that.""How wonderful, Basil!"
From LAWLER 194: Wilde added this to the typescript.
-
"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.
-
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.
-
When I find that I am growing old, I will kill myself."
From LAWLER 192: Wilde added this sentence in the typescript.
-
"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."
-
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.
-
"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.
-
-
codeberg.org codeberg.org
-
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, 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].
-
- Feb 2023
-
code.visualstudio.com code.visualstudio.com
-
"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." } } } },
-
-
stackoverflow.com stackoverflow.com
-
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; }
-
-
medium.com medium.com
-
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.
-
- Dec 2022
-
-
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.
Tags
Annotators
URL
-
-
www.typescriptlang.org www.typescriptlang.org
-
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.
-
- Sep 2022
-
www.typescriptlang.org www.typescriptlang.org
-
URL.parse
Where is the implementation of this function?
Tags
Annotators
URL
-
- Aug 2022
-
www.tektutorialshub.com www.tektutorialshub.com
-
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.
-
- May 2022
-
hasura.io hasura.io
-
In other typed languages, like TypeScript, Flow, Rust, or Haskell, all types are non-nullable by default, and you opt into nullability.
-
- Apr 2022
-
-
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?
-
It should be | { fallthrough: true } rather than | { fallthrough: boolean } I think (there's no reason you'd have false)
-
-
docdrop.org docdrop.org
-
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
-
- Feb 2022
-
www.youtube.com www.youtube.com
-
Title: React with Typescript Crash Course Published: APR/2021 Source: https://www.youtube.com/watch?v=jrKcJxF0lAU
-
-
code.visualstudio.com code.visualstudio.com
-
Common questions#
It may be worth highlighting that if
"module" = "commonjs"
intsconfig.json
, imports such asimport { something } from "module"
will be transpiled toconst module_1 = require("module")
. As a result,something
will not be available in the debug console, butmodule_1.something
instead.One may change
tsconfig.json
to include"module" = "es6"
and"moduleResolution" = "node"
, andpackage.json
to include"type" = "module"
, but in this case imports must include the file extension.
-
- Dec 2021
- Nov 2021
-
github.com github.com
-
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>).
-
add ! to the end of the var that is being spread. E.g. [{}, ...payload!]
-
-
www.typescriptlang.org www.typescriptlang.org
-
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.
-
Animal & { honey: boolean }
-
Extending a type via intersections
-
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.
-
-
github.com github.com
-
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);
Tags
Annotators
URL
-
-
-
const palette: { [key: string]: string } = {...
-
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 }
-
what is the TypeScript Way™ of handling the implicit any that appears due to object literals not having a standard index signature?
-
fresh (i.e. provably do not have properties we don't know about)
-
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.
-
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.
-
type PaletteColors = keyof typeof palette type Palette = { [Color in PaletteColors]: string }
-
Generate type with the index signature: interface RandomMappingWithIndexSignature { stringProp: string; numberProp: number; [propName: string]: string | number | undefined; }
-
we have no way to know that the line nameMap[3] = "bob"; isn't somewhere in your program
Tags
- javascript: objects: can't be sure what properties may have been added
- syntactic coincidence
- TypeScript: keyof
- coincidence
- TypeScript: index signature
- principle of least surprise
- TypeScript: fresh (provably do not have properties we don't know about)
- good point
- object literal
- official preferred convention / way to do something
- TypeScript
- no way to know / can't be sure whether _
- TypeScript: mapped type
Annotators
URL
-
-
www.reddit.com www.reddit.com
-
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.
-
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 }
-
-
github.com github.com
-
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; }
-
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.
-
-
github.com github.com
-
-
// Second case (unexpected) interface C { [x:string]: number } interface D { x: number } const d: D = { x: 1 }; const c: C = d; // error // Type 'D' is not assignable to type 'C'. // Index signature is missing in type 'D'.
-
-
stackoverflow.com stackoverflow.com
-
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.
-
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.
-
-
-
Check whether a value is defined (non-nullable), meaning it is neither `null` or `undefined`. This can be useful as a type guard, as for example, `[1, null].filter(Boolean)` does not always type-guard correctly.
-
-
-
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.
-
-
-
export type Simplify<T> = {[KeyType in keyof T]: T[KeyType]};
-
-
-
Having actual functions here is a non-goal. This package is for types only, meaning nothing ends up compiled into actual JS code.
-
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.
-
- Oct 2021
-
-
function applyDefaults(fetchFn: typeof fetch, defaults: Required<Parameters<typeof fetch>[1]>)
-
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:
-
- Sep 2021
-
www.sanity.io www.sanity.io
-
-
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.
-
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)!
-
-
stackoverflow.com stackoverflow.com
-
"types": ["node", "svelte"
-
-
betterprogramming.pub betterprogramming.pub
-
"paths": { "@/*": ["*"]}
-
-
github.com github.com
-
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!
-
-
blog.johnnyreilly.com blog.johnnyreilly.com
-
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.
-
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.
-
-
- Aug 2021
-
github.com github.com
-
const allRoles: string[] = Object.values(Role)
helped me!
-
-
github.com github.com
-
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.
-
I think a more natural/appropriate behavior for type signature of includes would be for the literal types to be widened.
-
-
-
This isn't too restrictive, and provides a nice type type guard.
-
function includes<T, U extends T>(arr: readonly U[], elem: T): elem is U { return arr.includes(elem as any); }
-
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.
-
Please read https://stackoverflow.com/questions/41750390/what-does-all-legal-javascript-is-legal-typescript-mean
-
See #14520 for discussion of upper-bounded generics.
Tags
- developer's intention
- relationship between
- getting in the way
- making it too easy to do the wrong thing
- TypeScript: type guards
- TypeScript: generics: upper-bounded
- intention
- making it easy to do the right thing
- caveat
- TypeScript: cost of using (tax)
- javascript
- TypeScript
- TypeScript: generics
Annotators
URL
-
-
github.com github.com
-
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;
-
-
stackoverflow.com stackoverflow.com
-
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;
-
const list = ['a', 'b', 'c'] as const; // TS3.4 syntax type NeededUnionType = typeof list[number]; // 'a'|'b'|'c';
-
This type of assertion causes the compiler to infer the narrowest type possible for a value, including making everything readonly.
"infer"?
-
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.
-
Or, maybe better, interpret the list as a tuple type: const list: ['a','b','c'] = ['a','b','c']; // tuple
-
One problem is the literal ['a','b','c'] will be inferred as type string[], so the type system will forget about the specific values.
-
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.
-
-
github.com github.com
-
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
-
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:
-
* 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
-
no plans to reduce empty cases to never more aggressively to help developers exclude weird/absurd/accidental cases
-
As a design decision, TypeScript does not collapse that type to `never` (although it could).
-
candidate is Dog { // compiler recognizes that Dog | T can narrow to T
-
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}
-
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 { … }
-
You can't just move 'side-ways' between unrelated types; you need to move either up or down the lattice.
-
-
stackoverflow.com stackoverflow.com
-
The best way to do this is to derive the type Format from a value like an array which contains all of the Format literals.
-
So is @Ryan Cavanaugh's answer the only viable solution? It seems extremely verbose...
-
My question is specifically if there is a way to do user defined type guards using the type itself
-
-
stackoverflow.com stackoverflow.com
-
function isKeyOfMcuParams(x: string): x is keyof McuParams { switch (x) { case 'foo': case 'bar': case 'baz': return true; default: return false; } }
-
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)?
-
-
charlypoly.com charlypoly.com
-
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
-
[K in keyof User]-?:
-
It means that when having a type guard:TypeScript and JavaScript runtime are tied to the same behaviour.
-
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.
-
This “gap” between what we call “runtime” and “static analysis” can be filled using TypeScript Type Guards.
-
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.
-
-
dev.to dev.to
-
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.
-
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'
-
function hasKey<O>(obj: O, key: PropertyKey): key is keyof O { return key in obj }
-
-
stackoverflow.com stackoverflow.com
-
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.
-
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.
-
If you really don't want to use any, you could use an empty interface - {} - instead:
-
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"; }
-
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.
-
-
stackoverflow.com stackoverflow.com
-
const isValidMethodForHandler = <T extends { [i: string]: any }>(handler: T) => ( method: string ): method is Extract<keyof T, string> => Object.keys(handler).indexOf(method) !== -1;
-
- Jul 2021
-
stackoverflow.com stackoverflow.com
-
In 2.8 you can use conditional types to achieve a similar effect
-
type CReturn<C, K extends keyof C> = C extends Array<any> ? C[number] : C[K];
-
Prior to 2.9 keyof only returned string indexes, in 2.9 this will include numeric and symbol keys.
-
const test = new Person(TestPerson).at("name").at("name")
-
-
stackoverflow.com stackoverflow.com
-
type FooType = { // interfaces or classes of course also possible bar: string; } type BarType = FooType['bar']; // BarType is a string now
-
-
stackoverflow.com stackoverflow.com
-
You can use this format to get the member type: type InputType = typeof input[number];
-
- Jun 2021
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
basarat.gitbook.io basarat.gitbook.ioClasses1
-
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) { }}
-
-
babeljs.io babeljs.io
-
we now support let x: typeof import('./x');, added in TypeScript 2.9
Tags
Annotators
URL
-
-
disqus.com disqus.com
-
The answer is no, we use a pattern where we do this, and have a `static` method for manufacturing the constructor.e.g.static from({prop1, prop2}) => new this(public prop1, public prop2)
-
-
news.ycombinator.com news.ycombinator.com
-
TypeScript definitions don't block and VS Code does not warn for `indices.forEach(console.log)`
Tags
Annotators
URL
-
-
prettier.io prettier.io
-
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.
Tags
Annotators
URL
-
- May 2021
-
github.com github.com
Tags
Annotators
URL
-
- Jan 2021
-
www.reddit.com www.reddit.com
-
Simple answer: If you need the interface in in another module.
-
-
github.com github.com
-
Just use import type {AnimType}... instead
Solves error for me:
export 'InterfaceName' was not found in
-
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.
-
-
learnxinyminutes.com learnxinyminutes.com
-
{ 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..
-
- Nov 2020
-
github.com github.com
-
Make this library Typescript first
-
-
-
typedoc.org typedoc.orgHome1
Tags
Annotators
URL
-
-
github.com github.com
-
// 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
-
-
github.com github.com
-
You can either use require to bypass typescript special import.
-
You may also use the package typings-for-css-modules-loader instead of css-loader to automatically generate typescript .d.ts files in order to help resolve any css/scss styles
-
-
github.com github.com
-
Typescript support
-
-
stackoverflow.com stackoverflow.com
-
Since Typescript 3.0 this can be done with Project References.
-
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,
-
-
- Oct 2020
-
firebase.google.com firebase.google.com
-
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
-
-
formvalidation.io formvalidation.io
-
Type safety. Entire codebase is written in TypeScript.
-
-
basarat.gitbook.io basarat.gitbook.io
-
TypeScript provides you with the ability to use something other than React with JSX in a type safe manner.
Tags
Annotators
URL
-
-
basarat.gitbook.io basarat.gitbook.io
-
github.com github.com
-
When using TypeScript, cast the type of file.contents on your side.
-
-
-
And yes, template tags cannot have TS right now.
-
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.
-