8 ms·
An introduction to type programming in TypeScript
- Graffur 5y agoMy main issue with TypeScript is the errors or warning in vscode are always awful edit: I am used to working with Java in Eclipse where the type warnings make much more sense
- yingliu4203 5y agoIt's eye-opening to know the Turing completeness of TypeScript' type programming. It is fun and insightful to know this fact. The examples are simple and to the point.
- udbhavs 5y agoThis really shows that there is a lot of potential for a native tsc alternative (like the one that was on the front page recently) to shine in terms of performance
- nlitened 5y agoI think it shows a lot of potential to turn TypeScript to what C++ has become.
- webstrand 5y agoUnlikely, types intentionally cannot affect the emitted JavaScript. You can always get raw JavaScript from TypeScript code by blindly erasing the type annotations (and transforming a few special syntaxes).
- tamebadger 5y agoI just remembered this blog post, maybe that's the one that was on the front page recently ? https://kdy1.dev/posts/2022/1/tsc-go https://kdy1.dev/posts/2022/1/tsc-go Ok yup, definitely that one, https://news.ycombinator.com/item?id=30074414 https://news.ycombinator.com/item?id=30074414
- mingyeow 5y agoThis is fantastic writing: After writing TypeScript for a while, it occurred to me that the TypeScript language actually consists of two sub-languages - one is JavaScript, and the other is the type language. For the JavaScript language, the world is made of JavaScript values; for the type language, the world is made of types.
- brabel 5y agoThis is called a "biformity". There was a great post about this the other day: https://hirrolot.github.io/posts/why-static-languages-suffer-from-complexity# https://hirrolot.github.io/posts/why-static-languages-suffer...
- avgcorrection 5y agoAnd: https://news.ycombinator.com/item?id=29996240 https://news.ycombinator.com/item?id=29996240
- benrbray 5y agoYou might be interested to learn that in languages like Coq with dependent types, the difference between type-level and value-level languages (almost) disappears! Check out the Software Foundations book [1]. [1] https://softwarefoundations.cis.upenn.edu/ https://softwarefoundations.cis.upenn.edu/
- chana_masala 5y agoHere's an implementation of a prime finding algorithm in pure (only type-level) Typescript. type IsPrime< MaybePrime extends number, NumAsTuple extends unknown[] = [], RemainderAsTuple extends unknown[] = NumAsTuple, > = MaybePrime extends NumAsTuple["length"] ? NumAsTuple["length"] extends RemainderAsTuple["length"] ? NumAsTuple["length"] extends (1 | 2 | 3 | 4 | 5 | 6) ? NumAsTuple["length"] extends (1 | 2 | 3 | 5) ? true : false : NumAsTuple extends [infer _, infer _, infer _, infer _, infer _, infer _, ...infer Rest] ? IsPrime<MaybePrime, NumAsTuple, Rest> : false : RemainderAsTuple["length"] extends (1 | 2 | 3 | 4 | 5 | 6) ? RemainderAsTuple["length"] extends (1 | 5) ? true : false : RemainderAsTuple extends [infer _, infer _, infer _, infer _, infer _, infer _, ...infer Rest] ? IsPrime<MaybePrime, NumAsTuple, Rest> : false : IsPrime<MaybePrime, [...NumAsTuple, 1]>;
- janjones 5y agoCool. How large prime can it detect before it hits the recursion limit?
- deleted 5y ago[deleted]
- bsimpson 5y ago857
- deleted 5y ago[deleted]
- aastronaut 5y agothank you! here[1] it is in action in the playground. [1]: https://www.typescriptlang.org/play?#code/C4TwDgpgBAkgzgBQE4EsC2EA8AoKeoCyAhiAEYTLrQQAewEAdgCZxQMCua5SANLvgDlOAQTgAVdmAA21OoxZR2DANYMA9gHcGAbQC6UALxQ9ffFABKENERTMISUROmz6zVktWad+o0LSPJGVMoAD5DfjxiMgpUDChaVwU-AOdtACIZBgBzYAALNN0I-AB+KGTxQIh0zJz8-QT5VktrWyZ7FJlqxlqCorNS8qdOjO68gvi5NygACgBGKAAfKAAmRagAZjWAFjWAVjWANgBKPrMoAZEK1JHssfrJhTm11aXNpd2Ts6-zqGAkdggpy+AC4oAAzIhSOCA774UGDSoTRKsbS2MH2KAAfR4UDRGOxuIY6KQWJxeJJBPJpMJxOpADoGVTLHBgIVYf1YIhYlgouRKBgcQjnDjmcAQkCzqCIVCYd9Qc0bHYHFdhjU7kjGjN5ksXhttntDp92aUFa12iqqjcevdkVq9kb2T8-gCJWYpZDoa6oPKrIq2sqhi5NaiifiyaGKeHaZSI9SqTHoziGXSmRAWWzHT94PyeSQ+dzBZdAyK02KvXh3TLTqDs9zMLyYlQcdpk0KglBZroQgBubDYUCQTk5+ZGWtUTCzHv98DQMcYVajrnj5ZTgezpcYTaLnOYdarmdD7k7bd1rb7wdziD7E-j3bn9c5g6GQ-jg73l8YADsz8vmE-78vAAOH8NywQCANAgBOECd0giDhwABhgutZgQqdpwvUDdmvD8sGwqcgA https://www.typescriptlang.org/play?#code/C4TwDgpgBAkgzgBQE4...
- duped 5y agoI think people focus on the "turing complete" part of type checking a bit too much - what's more compelling (and a real design decision) is that when designing a type system you need to choose if the type checking algorithm is decidable. That's not usually an accident, since when implementing the system you need to write the type checker, and you'll see quite plainly if it has an infinite loop case.
- ReleaseCandidat 5y agoA turing complete type system is undecidable.
- sfvisser 5y agoThe article seems to be mixing up type synonyms with type variables. Type variables have an actual well defined meaning. They act like variables that can be instantiated during inference/checking, analogue to how variables in the expression language get instantiated at runtime.
- rendall 5y ago> Type variables have an actual well defined meaning. In TypeScript or JavaScript? Can you say more?
- sfvisser 5y agoType variables are sometimes called generics and a part of the type language, so JavaScript doesn’t have them. Typescript, but also Rust, Haskell, Java, the ML-family have them. Type variables abstract over types and are analogous to function parameters at the values level. Think the ‘T’ in ‘List<T>’.
- rendall 5y agoThanks
- evolveyourmind 5y agoHere’s an implementation of lambda calculus (which is TC) at type level in TypeScript: https://github.com/EvolveYourMind/ts-lambda-calc https://github.com/EvolveYourMind/ts-lambda-calc And here a type-level RegExp matcher: https://github.com/EvolveYourMind/ts-regexp https://github.com/EvolveYourMind/ts-regexp
- phpnode 5y agoAnother example, SQL-database-in-the-typescript-typesystem here https://github.com/codemix/ts-sql https://github.com/codemix/ts-sql This would have been much easier if I'd had ts-regexp at the time :)
- evolveyourmind 5y agoI was actually inspired by your ts-sql project! Amazing work
- garmigula 5y agoCool introduction, now I'm one step closer to typing the technical interview https://aphyr.com/posts/342-typing-the-technical-interview https://aphyr.com/posts/342-typing-the-technical-interview
- forgotmyoldacc 5y agoI might just be not as intelligent as the average TypeScript developer, but I find the complexity with the type system off-putting. There's 5 different ways to type something, and learning a new type language isn't what I wanted when I just needed my JavaScript to be typed. It's too bad Flow has lost the typed-JS battle, I find the syntax to be a lot easier to use.
- schwartzworld 5y agoTypescript can type all your existing JS, but you're right it's crazy complex. TS only becomes manageable when you stop treating the compiler as an add-on and treat it as a guide.
- throw_m239339 5y ago> and learning a new type language isn't what I wanted when I just needed my JavaScript to be typed. Well, good news, you can use Typescript's compiler as a Js static code analyzer without writing a single line of Typescript!
- dataviz1000 5y agoSomeone created a very nice curated list of advanced Typescript videos. [0] After watching and working through them, I have not been stumped with more complex typing problems. [0] https://www.youtube.com/playlist?list=PLw5h0DiJ-9PBIgIyd2ZA1CVnJf0BLFJg2 https://www.youtube.com/playlist?list=PLw5h0DiJ-9PBIgIyd2ZA1...
- amitport 5y agoStrongly disagree. It is OK if you prefer no solution to some complex typing needs that are solved with complex syntax in Typescript. Most of Typescript is optional. It's not trivial to think of simpler alternatives to much of the problems Typescript is tackling. (And if you have any simplifying syntax suggestions that don't break typing it will be interesting to read)
- douglaswlance 5y agoYou almost never need to reach for advanced typing unless you're writing a generic library.
- ReleaseCandidat 5y agoHaving a Turing complete type system is not what you normally want to have, that (it means to have undecidable type checking) makes tooling (and the compiler) way more complex and difficult. GitHub issue about the Turing completeness: https://github.com/microsoft/TypeScript/issues/14833 https://github.com/microsoft/TypeScript/issues/14833 Proof of Turing completeness: https://gist.github.com/hediet/63f4844acf5ac330804801084f87a6d4 https://gist.github.com/hediet/63f4844acf5ac330804801084f87a...
- gpderetta 5y agoWhich widely used statically typed languages do not have a Turing complete type system? C, probably Go?
- ReleaseCandidat 5y agoDepends on your definition of 'widely used' ;). Using Tiobe's top 20: I'd guess Swift, Delphi, Fortran and Go C++, Java, Rust, Haskell, Typescript have a Turing complete type system. C#: don't know, could be.
- gpderetta 5y agoOf the list above, I'm most surprised that Swift doesn't have a Turing complete type system.
- ReleaseCandidat 5y agoI wanted to answer with "because Swift's type checking is decidable", but that has changed (with SE-0142 and SE-0157) - allowing recursion. So, it is 'at least' undecidable now. https://forums.swift.org/t/swift-type-checking-is-undecidable/39024 https://forums.swift.org/t/swift-type-checking-is-undecidabl...
- gpderetta 5y agoYes, I did see that bit. Incidentally google provides terrible results for 'swift type system turing complete'.
- mccorrinall 5y agoI love writing code with typescript, but some things just make it harder than necessary, for example using environment variables. If I want to use process.env.NODE_ENV I first have to create a new environment.d.ts, declare the interfaxe and export an empty object just so the typescript compiler is satisfied. It sometimes just adds too much boilerplate. https://stackoverflow.com/a/53981706 https://stackoverflow.com/a/53981706
- wruza 5y agoTypescript’s type narrowing is useful for this exact situation: // v is any or unknown if (typeof v !== "string") { throw new Error("oops") } // v is now string You can’t get runtime type correctness by deceiving typescript into it.
- lobstrosity420 5y agoDon't do this! What TS is trying to tell you is that this variable may not have been set in the environment, and thus it's value inside of the program will evaluate to `undefined`. What you are doing when you create the environment.d.ts file is forcing the transpiler to assume the variable will have been set, which is not really true. The program may still end up being executed in an environment in which the variable was not set. Instead, what I like to do is create a config file in your project where you export an object containing all configuration values for your project. There, you can set default values for variables coming from the environment. In this way, you guarantee a value will be present for the execution of your program: export const config = { dbConnectionString: process.env.DB_CONNECTION || 'localhost:27017', nodeEnv: process.env.NODE_ENV || 'development', } Remember that the NodeJS runtime guarantees the setting of no environment variables. The NODE_ENV variable is simply a convention that was started by express.
- capableweb 5y ago> Remember that the NodeJS runtime guarantees the setting of no environment variables. The NODE_ENV variable is simply a convention that was started by express. You're right that the runtime itself doesn't guarantee any env vars. I'm not sure who used it first, but npm also sets NODE_ENV (and some other env vars I think) in its different lifecycles, depending on if you provide the --production/--no-production flag when running it. But not sure if that came after or before express started using it.
- nvegater 5y agoI really like JS/TS Combo. My only critic is the Enums - particularly the String enums. It is really an absolute mess.
- wruza 5y ago“Bare” enums are not better either. No introspection, bad debug-ability (you can’t print them in a human-readable way). Typescript enums are a good tradeoff between just string|string|… types and pure integers (or whatever type you assign to them). The former’s literals are indistinguishable from string literals at readsourcestime. The latter creates issues at debugtime.
- epolanski 5y agoUnion types are the way to go in 99% of cases you need enums.
- _jumble 5y agoYes, and generating those unions from a const array gives you even further flexibility with runtime access: `const myStrArray = ["a", "b", "c"] as const; type MyStrType = typeof myStrArray[number];`
- deleted 5y ago[deleted]
- nakovet 5y agoThe author started the topic really well, be defining a separation between Javascript/Typescript. I find the examples that followed to be a demonstration without purpose. After reading them I don't know when to use them, he mentions "type gymnastics" at the end and I find that most of the examples are demonstrations of type gymnastics. I work on a large Typescript codebase and rarely I need to do abstract typing in order to get something done, Typescript can be used in a very direct and objetive manner and it's usually the route I prefer.