#typescript union
Explore tagged Tumblr posts
codeonedigest · 2 years ago
Video
youtube
TypeScript Interface Alias Union Tutorial for JavaScript Developers Full Video Link -   https://youtu.be/j7KzDovCqmU Check out this new video on the CodeOneDigest YouTube channel! Learn Interface, Alias & Union in typescript. Learn how to use Interface & Objects, how to use Alias & Union in typescript language. #video #typescript #interface #alias #union #nodejs #javascript #codeonedigest@java @awscloud @AWSCloudIndia @YouTube @codeonedigest #typescript #javascript #typescript #javascript #typescripttutorial #learntypescript #typescriptforbeginners #typescripttutorialforbeginners #typescriptinterface #typescriptinterfaceprops #typescriptinterfacejson #typescriptalias #typescriptunion #typescriptfullcourse #typescriptcrashcourse #typescriptexplained #typescriptproject #typescriptprojectsforbeginners #typescriptprojecttutorial #typescripttutorialforjavascriptdevelopers #typescriptguide #typescriptcompleteguide
1 note · View note
learn-from-my-experience · 2 years ago
Text
Every TypeScript example and tutorial I've come across so far mainly focuses on language features, static typing, and working with Visual Studio. However, I couldn't find much guidance on how to use TypeScript effectively with JavaScript and the DOM.
I remember having the same question a while back, just like Johnny on Stack Overflow. "Can we use TypeScript to manipulate the DOM?" This question motivated me to dive deeper and figure it out, and I'm here to share what I've learned.
Configuration: Using TypeScript for DOM manipulation is straightforward, but it does require some configuration. You'll need to include the specific types for DOM access, which aren't available by default in TypeScript. To do this, you must explicitly configure the TypeScript compiler to include the "dom" library in the compilerOptions section of your tsconfig.json file. It's worth noting that the decision not to include these types by default might suggest that TypeScript's creators initially intended it more for server-side development with Node.js than for front-end work.
/** tsconfig.json - Configuration file in the project folder for the TypeScript compiler */ { "compilerOptions": { "lib": [ "es2015", "dom" ], "strict": true, "target": "es2015" } }
Hello World: In this article, I'll create a simple "Hello, world!" program to demonstrate how to use the DOM in TypeScript. Since this is my first post about TypeScript, I'll cover the basics of working with DOM types and address a common challenge that beginners might encounter. Please note that I won't be discussing DOM events in this post; that's a topic for a future article.
Let's start with the basics by changing the inner text value of an existing HTML element. I began by creating an HTML file with a standard HTML5 boilerplate, including an <h1> element with the id "greeter" in the body.
<!DOCTYPE html> <html lang="en"> <head> <!-- ... --> </head> <body> <h1 id="greeter">Hello</h1> </body> </html>
Next, I opened a new TypeScript file and added the following code:
let greeter: HTMLHeadingElement = document.getElementById("greeter") as HTMLHeadingElement; greeter.innerText = "Hello world!";
Tumblr media
In this code, I created a variable called greeter and assigned the type HTMLHeadingElement to it. The HTMLHeadingElement type is defined in the "dom" library we added to the configuration. It tells the TypeScript compiler that greeter expects an HTML heading element and nothing else. Then, I assigned the greeter to the value returned by the getElementById function, which selects an element by its ID. Finally, I set the inner text of the greeter element to "Hello world."
When I compiled the code with the following command:
tsc script.ts
Tumblr media
It produced the following error:
Type 'HTMLElement | null' is not assignable to type 'HTMLHeadingElement'. Type 'null' is not assignable to type 'HTMLHeadingElement'.
It's a bit frustrating, but TypeScript is doing its job. This error means that I tried to assign a greeter, which is of type HTMLHeadingElement, with an object of type HTMLElement that the getElementById method returned. The HTMLElement | null in the error message indicates that the method's return value can be either of type HTMLElement or null.
To address this, I used TypeScript's type assertion feature to tell the compiler that the element returned by getElementById is indeed a heading element, and it doesn't need to worry about it. Here's the updated code:
let greeter: HTMLHeadingElement = document.getElementById("greeter") as HTMLHeadingElement; greeter.innerText = "Hello world!";
Tumblr media
With this change, the compilation was successful. I included the script.js file generated by the compiler in the HTML document and opened it in a browser.
Tumblr media
Decoration Time: Now that I've confirmed that everything works as intended, it's time to make the page more visually appealing. I wanted a font style that was informal, so I chose the "Rock Salt" font from Google Fonts. I imported it into my stylesheet, along with "Dancing Script" as a secondary font, using CSS imports. I then added a few more elements to the HTML document, centered all the text using CSS flexbox, added a background from UI gradients, and adjusted the positions of some elements for proper arrangement. The page now looked beautiful.
Animation: To add a finishing touch, I wanted to include a background animation of orbs rising to the top like bubbles. To create the orbs, I decided to use <div> elements. Since I wanted several orbs with different sizes, I split the task into two steps to simplify the work.
First, I created a common style for all the orbs and defined a custom animation for the orbs in CSS. Then, I created the orbs dynamically using TypeScript. I created a set number of <div> elements, assigned them the pre-defined style, and randomized their sizes, positions, and animation delays to make them appear more natural.
Here's an excerpt of the code for creating the bubbles:
function createBubbles() { for (let i = 0; i < bubbleCount; i++) { let div: HTMLDivElement = document.createElement("div") as HTMLDivElement; let divSize = getSize(); div.style.left = getLeftPosition() + "px"; div.style.width = divSize + "px"; div.style.height = divSize + "px"; div.style.animationDelay = i * randomFloat(0, 30) + "s"; div.style.filter = "blur(" + randomFloat(2, 5) + "px)"; div.classList.add("bubble"); bubbleBuffer.push(div); } console.log("Bubbles created"); }
After creating the orbs, I added them to the DOM and started the animation:
function releaseBubbles() { createBubbles(); for (let i = 0; i < bubbleCount; i++) { containerDiv.appendChild(bubbleBuffer[i]); } console.log("Bubbles released"); }
And with that, the animation of orbs rising like bubbles was set in motion.
Here's the final output:
youtube
You can find the complete code in this repository.
Conclusion: While writing this article and creating the example, I realized the involvement of advanced concepts like type assertion and union types. I now understand why the authors of those tutorials didn't include them; introducing them could confuse beginners. It's best to learn TypeScript thoroughly before venturing into DOM manipulation.
In my example, I skipped null checking when fixing the type mismatch error, as it seemed unnecessary for the demonstration. However, in real projects, it's important to check for null values to avoid runtime errors. I also didn't
0 notes
doubleunion · 6 months ago
Text
The making of the SF family swim map!
This is a technical blog post showcasing a project (swim.joyfulparentingsf.com) made by Double Union members! Written by Ruth Grace Wong.
Emeline (a good friend and fellow DU member) and I love swimming with our kids. The kids love it too, and they always eat really well after swimming! But for a long time we were frustrated about SF Rec & Park's swim schedules. Say today is Wednesday and you want to swim, you have to click on each pool's website and download their PDF schedule to check where and when family swim is available, and the schedules change every few months.
Emeline painstakingly downloaded all the PDFs and manually collated the schedules onto our Joyful Parenting SF blog. The way Rec and Parks structure their schedule assumes that swimmers go to their closest pool, and only need the hours for that particular pool. But we found that this was different from how many families, especially families with young children, research swim times. Often, they have a time where they can go swimming, and they are willing to go to different swimming pools. Often, they’re searching for a place to swim at the last minute. Schedules hence need to allow families to search which pools are open at what time for family swimming. Initially, we extracted family swim times manually from each pool’s pdf schedule and listed them in a blog post. It wasn't particularly user friendly, so she made an interactive map using Felt, where you could select the time period (e.g. Saturday Afternoon) and see which pool offered family swim around that time.
Tumblr media
But the schedules change every couple of months, and it got to be too much to be manually updating the map or the blog post. Still, we wanted some way to be able to easily see when and where we could swim with the kids.
Just as we were burning out on manually updating the list, SF Rec & Park released a new Activity Search API, where you can query scheduled activities once their staff have manually entered them into the system. I wrote a Python script to pull Family Swim, and quickly realized that I had to also account for Parent and Child swim (family swim where the parents must be in the water with the kids), and other versions of this such as "Parent / Child Swim". Additionally, the data was not consistent – sometimes the scheduled activities were stored as sub activities, and I had to query the sub activity IDs to find the scheduled times. Finally, some pools (Balboa and Hamilton) have what we call "secret swim", where if the pool is split into a big and small pool, and there is Lap Swim scheduled with nothing else at the same time, the small pool can be used for family swim. So I also pulled all of the lap swim entries for these pools and all other scheduled activities at the pool so I could cross reference and see when secret family swim was available.
We've also seen occasional issues where there is a swim scheduled in the Activity Search, but it's a data entry error and the scheduled swim is not actually available, or there's a Parent Child Swim scheduled during a lap swim (but not all of the lap swims so I can't automatically detect it!) that hasn't been entered into the Activity Search at all. Our friends at SF Kids Swim have been working with SF Rec & Park to advocate for the release of the API, help correct data errors, and ask if there is any opportunity for process improvement.
At the end of the summer, Felt raised their non profit rate from $100 a year to $250 a year. We needed to pay in order to use their API to automatically update the map, but we weren't able to raise enough money to cover the higher rate. Luckily, my husband Robin is a full stack engineer specializing in complex frontends such as maps, and he looked for an open source WebGL map library. MapBox is one very popular option, but he ended up going with MapLibre GL because it had a better open source license. He wrote it in Typescript transpiled with Vite, allowing all the map processing work to happen client-side. All I needed to do was output GeoJSON with my Python script.
Tumblr media
Originally I had been running my script in Replit, but I ended up deciding to switch to Digital Ocean because I wasn't sure how reliably Replit would be able to automatically update the map on a schedule, and I didn't know how stable their pricing would be. My regular server is still running Ubuntu 16, and instead of upgrading it (or trying to get a newer version of Python working on an old server or – god forbid – not using the amazing new Python f strings feature), I decided to spin up a new server on Almalinux 9, which doesn't require as frequent upgrades. I modified my code to automatically push updates into version control and recompile the map when schedule changes were detected, ran it in a daily cron job, and we announced our new map on our blog.
Soon we got a request for it to automatically select the current day of the week, and Robin was able to do it in a jiffy. If you're using it and find an opportunity for improvement, please find me on Twitter at ruthgracewong.
As a working mom, progress on this project was stretched out over nearly half a year. I'm grateful to be able to collaborate with the ever ineffable Emeline, as well as for support from family, friends, and SF Kids Swim. It's super exciting that the swim map is finally out in the world! You can find it at swim.joyfulparentingsf.com.
6 notes · View notes
codezup · 2 months ago
Text
Unlock TypeScript's Full Potential: Advanced Type System Techniques
1. Introduction TypeScript is a statically typed superset of JavaScript that adds powerful type system features, enabling developers to catch errors early and improve code maintainability. This tutorial will explore advanced TypeScript type system techniques, covering union types, intersection types, conditional types, and more. What You Will Learn Advanced TypeScript type system features. How…
0 notes
atplblog · 2 months ago
Text
Price: [price_with_discount] (as of [price_update_date] - Details) [ad_1] Unlock TypeScript 5 patterns for durable, maintainable apps with modern techniques.Key Features: - Avoid common pitfalls and anti-patterns in TypeScript app development- Leverage functional and reactive paradigms for effective TypeScript development- Discover how to improve your application's code reusability and testability- Purchase of the print or Kindle book includes a free PDF eBook Book Description: Design patterns are the foundation of many world-class software applications, from commercial solutions to open-source projects. This guide equips you with the skills to architect robust, scalable, and maintainable TypeScript 5 applications. Whether you're looking to master modern TypeScript or apply proven software architecture patterns effectively, this book is your go-to resource.Written by Theofanis Despoudis, a recognized TypeScript expert, this second edition is fully updated with TypeScript 5's latest features, including improved type inference, union enums, and decorators. These updates will help you write cleaner, more maintainable code that adapts to future changes. You'll dive into classic Gang of Four design patterns through both traditional and modern real-world implementations, gaining hands-on experience with practical applications. You'll also gain a clear understanding of the power of functional and reactive programming patterns specifically designed for idiomatic TypeScript development.By the end of this book, you'll be able to identify and apply the right design pattern for any scenario and craft well-structured, maintainable, and testable code. What You Will Learn: - Understand the principles of design patterns and their role in TypeScript development- Learn essential patterns, including creational, structural, and behavioral, with TypeScript- Differentiate between patterns and design concepts and apply them effectively- Gain hands-on experience implementing patterns in real-world TypeScript projects- Explore advanced techniques from functional and reactive programming paradigms- Write efficient, high-quality TypeScript code that enhances performance and flexibility Who this book is for: If you are a TypeScript developer working on frontend, backend, or full-stack applications looking to learn how to apply established design patterns to solve common programming problems instead of reinventing solutions, you'll find this book useful. Prior knowledge of design patterns is not necessary-all you need is basic TypeScript knowledge to get started with this book. Table of Contents- Getting Started with TypeScript 5- TypeScript Core Principles- Creational Design Patterns- Structural Design Patterns- Behavioral Design Patterns for Object Communication- Behavioral Design Patterns for Managing State and Behavior- Functional Programming with TypeScript- Reactive and Asynchronous Programming- Developing Modern and Robust TypeScript Applications- Anti-Patterns and Workarounds- Exploring Design Patterns in Open Source Architectures ASIN ‏ : ‎ B0DQPQ3RKQ Publisher ‏ : ‎ Packt Publishing; 2nd ed. edition (27 February 2025) Language ‏ : ‎ English Paperback ‏ : ‎ 424 pages ISBN-13 ‏ : ‎ 978-1835883228 Item Weight
‏ : ‎ 903 g Dimensions ‏ : ‎ 2.24 x 19.05 x 23.5 cm Country of Origin ‏ : ‎ India [ad_2]
0 notes
softwarily · 4 months ago
Text
1 note · View note
gagande · 8 months ago
Text
PureCode AI review | Optimization Techniques and Design Patterns
Application performance and maintainability are enhanced by optimization techniques and design patterns, integral aspects of TypeScript. From enforcing strict modes in TypeScript to maximize type checking and catch potential errors at compile-time, to using discriminated unions for type-safe state management and action handling in scalable applications, TypeScript offers a plethora of options for code optimization.
0 notes
tinchicus · 8 months ago
Text
TypeScript / Curso Inicial
Hoy toca el listado de todos los posts subidos sobre typescript. Ideal para repasar algun tema y sobre todo si te perdiste alguno. Espero les sea de utilidad y buen inicio de semana!
Bienvenidos sean a este post, hasta aqui todos los posts de nuestro curso inicial de typescript: Introduccion Instalacion Hola, TypeScript Proyecto de TypeScript Tipos basicos Libreria de terceros any let const Union de tipos Guardianes de tipos type enum undefined y null Operador condicional Operador de encadenamiento Coalescencia nula Asignacion…
0 notes
not-toivo · 10 months ago
Text
Matt Pocock's Total TypeScript: Essentials
Tumblr media
Some notes I made while reading this book:
Optional values in a tuple
Not only can a tuple have named values, it can have optional ones:
[name: string, year: number, info?: string]
[string, number, string?]
Dealing with an unknown
If we have obj of type unknown, and we want to get obj.prop of type string, this is how to do it correctly:
typeof obj === 'object' && obj && 'prop' in obj && typeof obj.prop === 'string'
If we refactor the expression above into a return value of a type guard, this would be its type signature:
(obj: unknown) => obj is {prop: string}
Destructuring values of union types (tuples vs. objects)
const [status, value]: ['success', User[]] | ['error', string] = await fetchData();
TS can then guess based on the type of the discriminant (the status variable) the type of the rest of the return value (the value variable), but wouldn't be able to do the same, if fetchData returned an object instead of tuple. An object type should be narrowed first, before we can destructure its value!
Dynamic keys
If we don't know, what keys the object may have during the lifetime of the program, we can have index signatures...
type DynamicKeys = { [index: string]: number; }
interface DynamicKeys { [index: string]: string; }
...or we can use Record helper type. Record type supports union types of type literals, unlike index signatures!
type DynamicKeys = Record<'name' | 'age' | 'occupation', boolean>
Read-only arrays
We can disallow array mutation by marking arrays and tuples as readonly, or using ReadonlyArray helper type:
const readOnlyGenres: readonly string[] = ["rock", "pop", "unclassifiable"];
const readOnlyGenres: ReadonlyArray<string> = ["rock", "pop", "unclassifiable"];
Read-only arrays/tuples can only be passed to functions that explicitly expect read-only arrays/tuples:
Matt's strange opinions on class methods
function printGenresReadOnly(genres: readonly string[]) { }
More helper types
Tumblr media
When Matt talks about the difference between arrow and function methods, he mentions only the different ways they handle this, but isn't a much more important distinction the fact that arrow methods are technically class properties, so will be copied on every instance of a class?
UPD: And later he recommends using arrow functions!
Tumblr media
This is extremely memory inefficient, right?
satisfies operator
Very useful thing I've never heard of before!
When a value isn't annotated with type, its type is inferred. When a value is annotated with type, its type is checked against the annotated type. When a value is followed with satisfies, its type is inferred (as if there were no annotation), but still checked against the constraint (as if there were an annotation).
Useful (?) type assertions
as any // turns off type checking for a particular value.
as unknown as T // cast a value to a completely unrelated type.
as const satisfies T // makes a value immutable, while checking it against a type.
Object.keys (user).forEach((key) => { console.log(user[key as keyof typeof user]); }) // by default TS infers return values of Object.keys() and for ... in as string[].
Excess properties
TS doesn't throw an error, when (1) a variable containing an object with excess properties is passed to a function, or (2) when an object with excess properties is returned by a callback. Both the variable and the return type of the callback should be annotated, if that is an issue.
Modules vs. scripts
Files with no import or export statement are treated by the compiler as scripts, executing in the global scope. The problem is, that's not how the distinction works in pure JS, so we can end up in sitiations like this...
Tumblr media
...just because the name variable already exists elsewhere. One way to fix this mistake (which I knew about) is by adding export {}; to the end of the file, turning it into a module from TS perspective. Another way (which I found out about just now) is by adding line "moduleDetection": "force" to the config file. Cool.
Recommended configuration (link)
Tumblr media
0 notes
if-you-fan-a-fire · 1 year ago
Text
"There was an exchange of thoughts with some. One of the assistant [prison] chaplains told one CO [Conscientious Objector] it was a pity he was hiding behind prison walls, the reply was quick: ‘That’s better than hiding behind a reversible collar.’ [The chaplain] tried to close the cell door, but the CO placed his foot in, and continued the talk, giving his views on his stand."
- George Ewan, ‘Prison Memories of George Ewan: Being the Experiences of a Conscientious Objector in the First Word War,’ typescript in the Archives of the Peace Pledge Union (London, n.d.), reprinted in Peter Brock, ed., 'These Strange Criminals': An Anthology of Prison Memoirs By Conscientious Objectors from the Great War to the Cold War. Toronto: University of Toronto Press, 2004. p. 74
0 notes
dreaminginthedeepsouth · 2 years ago
Text
* * * *
James Muilenburg BUT FOR ME, AS for most of us studying there in those days, there was no one on the faculty who left so powerful and lasting an impression as James Muilenburg. He was an angular man with thinning white hair, staring eyes, and a nose and chin which at times seemed so close to touching that they gave him the face of a good witch. In his introductory Old Testament course, the largest lecture hall that Union had was always packed to hear him. Students brought friends. Friends brought friends. People stood in the back when the chairs ran out. Up and down the whole length of the aisle he would stride as he chanted the war songs, the taunt songs, the dirges of ancient Israel. With his body stiff, his knees bent, his arms scarecrowed far to either side, he never merely taught the Old Testament but was the Old Testament.  He would be Adam, wide-eyed and halting as he named the beasts "You are . . . an elephant . . . a butterfly . . . an ostrich!"or Eve, trembling and afraid in the garden of her lost innocence, would be David sobbing his great lament at the death of Saul and Jonathan, would be Moses coming down from Sinai. His face uptilted and his eyes aghast, he would be Yahweh himself, creating the heavens and the earth, and when he called out, "Let there be light.'" There is no way of putting it other than to say that there would be light, great floods of it reflected in the hundreds of faces watching him in that enormous room. In more or less these words, I described him in a novel later, and when I showed him the typescript for his approval, he was appalled because it seemed to confirm his terrible fear that he was making a fool of himself. And, of course, if it hadn't been for his genius, for the staggering sincerity of his performance, he might almost have been right. It was a measure of folly as well as of strength and courage, I suppose, to let himself come so perilously close to disaster. "Every morning when you wake up," he used to say, "before you reaffirm your faith in the majesty of a loving God, before you say I believe for another day, read the Daily News with its record of the latest crimes and tragedies of mankind and then see if you can honestly say it again." He was a fool in the sense that he didn't or couldn't or wouldn't resolve, intellectualize, evade, the tensions of his faith but lived those tensions out, torn almost in two by them at times. His faith was not a seamless garment but a ragged garment with the seams showing, the tears showing, a garment that he clutched about him like a man in a storm. - Originally published in "Now and Then" Frederick Buechner
Tumblr media
@annalaura_art
502 notes · View notes
codeonedigest · 2 years ago
Video
youtube
TypeScript Interface Alias Union Tutorial for JavaScript Developers
0 notes
ivanca · 2 years ago
Text
ChatGPT can generate HTML/CSS based on simple ASCII mockups
I was pleasantly surprised to discover that ChatGPT 4 can interpret simple ASCII art and do a decent job converting simple designs into HTML/CSS; to quickly create the initial ASCII design I'm using this online tool https://asciiflow.com/ and for the prompt I have used "Generate HTML and CSS (using flexbox) based on the following ascii art:"
Some examples of the ASCII and the result:
Tumblr media
Result:
Tumblr media
Example #2:
Tumblr media
Result:
Tumblr media
For this last example the attempt to make it generate a SVG donut chart failed (it gave me a placeholder and suggested to use a JS library to do so instead), so I had to ask it to replace it with vertical bars which are easier to generate, I also had to ask it to "hardcode all countries that belong to the European Union even if its not practical or maintanable" because it was giving me a placeholder and suggesting to "Use an API" to fetch those, which is not bad advice but for quick mockups may not be desirable.
I tried more complicated task like making it animate an ASCII cat art using multiple elements (as they were "frames") but it consitently failed, it did seem to understand that it should show just one element each fraction or a second to the create the motion illusion but it failed on the artistic endeavor of modyfing existing ASCII art.
I hope you find this info helpful, and if you have insights of what works and what doesn't when using ASCII art on ChatGPT to mock up webpages (or anything else) feel free to share those in the comment section below or in the HN thread.
That's the end of the post but while you are here...
My name is Ivan and I'm a Full-stack programmer, I live in Colombia and I’m looking for a remote job as Full-Stack Engineer so if you or you company are interested in hiring just let me know! I'm also open to Visa Sponsorship opportunities (EU or US). I have more than 10 years of experience with JavaScript, as well as a few years with TypeScript, React, Python, PHP, Git and Node, as well as knowledge of good software practices such as SOLID architecture, unit testing, regression testing, e2e testing; if you are interested in hiring me please reach me at ivanca at gmail
0 notes
transienturl · 2 years ago
Text
also yes. sometimes my lack of productivity and comically bad sleep schedule are due to my brain problems and sometimes they are because, yeah, sure, I can teach you typescript better than your instructor can.
(do I know typescript? eh, not really. but I can extend from an interface, use a generic, and make a union "enum" from a const array, and that's good enough for government work, right?)
1 note · View note
codezup · 2 months ago
Text
Master TypeScript: Type Guards & Discriminated Unions Guide
Introduction TypeScript is a powerful superset of JavaScript that adds static typing, enabling developers to write safer and more maintainable code. Among its many features, Type Guards and Discriminated Unions stand out as particularly useful for handling complex type scenarios. This tutorial will guide you through mastering these concepts, enhancing your TypeScript skills and allowing you to…
0 notes
capeladev · 2 years ago
Text
Tumblr media
0 notes