News for hackers. Stuff that matters.
Re:A 'CSS reset' for TypeScript, improving types for common ... by quickthrower2 on Friday March 03, 2023 @03:03AM (#35007010)
With the ‘unknown’ type available is there a good case for ‘any’ anymore?

I really like the ‘unknown’ type. In catch statements for example the error is unknown but you can do dynamic checks to see what it is, then typescript lets you treat it that way.

Re:A 'CSS reset' for TypeScript, improving types for common ... by capableweb on Friday March 03, 2023 @03:22AM (#35007102)
For one, it signals different intent, which tends to be important in larger projects with more collaborators. The more you can make intentions obvious, the easier it'll be for others to understand and contribute.

A value whose type we don't know is different from a value which we know could be any type.

Re:A 'CSS reset' for TypeScript, improving types for common ... by bluepnume on Friday March 03, 2023 @03:34AM (#35007166)
Those sound like the same thing to me.
Re:A 'CSS reset' for TypeScript, improving types for common ... by blowski on Friday March 03, 2023 @03:58AM (#35007338)
Consider a ‘dump’ function. By design, it handles anything you throw at it - strings, objects, booleans, etc. It won’t change. That’s ‘Any’.

Whereas ‘Unknown’ might be a stepping stone to introduce a more specific type once all the use cases are known. I let it handle strings and integers, log a line about any other type that calls it, and continue behaviour as it is today.

Re:A 'CSS reset' for TypeScript, improving types for common ... by dtech on Friday March 03, 2023 @04:46AM (#35007627)
Such a `dump` function would be 100% the same with unknown, since all types can be converted to top types (both any and unknown in TS)
Re:A 'CSS reset' for TypeScript, improving types for common ... by badlucklottery on Friday March 03, 2023 @05:19AM (#35007817)
The difference comes when you interface with other well-typed code and want to convert from any/unknown down to a specific type.

For example:

  function handleString(s: string) {
    //...
  }

  declare const a: any;
  declare const u: unknown;

  handleString(a); // works with zero intervention

  handleString(u); // error: Argument of type 'unknown' is not assignable to parameter of type 'string'

  handleString(u as string); // works again with explicit re-typing
Re:A 'CSS reset' for TypeScript, improving types for common ... by capableweb on Friday March 03, 2023 @06:30AM (#35008217)
A dump function accepting "unknown" is signalling "I'm not sure what this function could handle, probably a lot of different types" vs accepting "any" where it's telling you "I can accept any type you throw at me".
Re:A 'CSS reset' for TypeScript, improving types for common ... by bigyikes on Friday March 03, 2023 @05:27AM (#35007862)
Here’s how I think about it, in much looser terms:

unknown = I don’t know

any = I don’t care

Often the implications are the same, but as you can intuit, any is a lot more relaxed.

Any will work anywhere because you just don’t care what the type is.

Unknown is stricter. It won’t work in cases where other types expect you to know what type you’re dealing with.

The compiler treats unknown very cautiously, whereas you can slap an any on pretty much anything.

Re:A 'CSS reset' for TypeScript, improving types for common ... by capableweb on Friday March 03, 2023 @06:29AM (#35008211)
They're the same as much as "1 + 1 = 2" and "2 + 0 = 2" is the same. The result might be the same ("any" and "unknown" accepting any type) but again, the intent is different (a value we know can be anything vs a value we don't know what type it'll have).
Re:A 'CSS reset' for TypeScript, improving types for common ... by spankalee on Friday March 03, 2023 @03:30AM (#35007150)
The TypeScript team has said that if they could do it over, `any` would behave like `unknown`.
Re:A 'CSS reset' for TypeScript, improving types for common ... by Kiro on Friday March 03, 2023 @04:38AM (#35007583)
That sounds extremely cumbersome. Sometimes I just want to throw an any on something and call a method on it without having to deal with types. How would unknown help with that? I can't call a method on a variable with unknown type.
Re:A 'CSS reset' for TypeScript, improving types for common ... by haburka on Friday March 03, 2023 @04:48AM (#35007642)
You can use ‘as’ to cast unknown to any type. This is extra typing but it does signify to other developers that you’re calling a function on an unverified object, which I believe makes the code more maintainable in the long run.
Re:A 'CSS reset' for TypeScript, improving types for common ... by anentropic on Friday March 03, 2023 @10:07AM (#35010549)
Why bother using typescript then?
Re:A 'CSS reset' for TypeScript, improving types for common ... by Kiro on Friday March 03, 2023 @11:06AM (#35011377)
That 1% won't invalidate the remaining 99%.
Re:A 'CSS reset' for TypeScript, improving types for common ... by golergka on Friday March 03, 2023 @05:21AM (#35007830)
This is a good thing for serious, long lasting projects. However, it could be an overkill for something fast and dirty.

One thing I love about typescript that I've never seen in other languages is that you can adjust the type checker exactly for the level of rigidness that project at hand needs. Any is okay for 200 LOC quick prototypes.

Re:A 'CSS reset' for TypeScript, improving types for common ... by Gigachad on Friday March 03, 2023 @05:33AM (#35007906)
This is a bit of a problem imo. It’s super easy to forget to add a type somewhere and then it just defaults to any. I’d prefer no implicit any so you have to knowingly set something as untyped.

It’s also just flat out impossible in many other languages because the compiler actually needs to know the types for performance reasons.

Re:A 'CSS reset' for TypeScript, improving types for common ... by gchq-7703 on Friday March 03, 2023 @06:00AM (#35008056)
This is possible with a single `tsconfig.json` change[0]. This is also the default mode if you've set the 'strict' flag.

[0] https://www.typescriptlang.org/tsconfig#noImplicitAny

Re:A 'CSS reset' for TypeScript, improving types for common ... by mablopoule on Friday March 03, 2023 @06:05AM (#35008093)
Yes, exactly.

Typescript managed to be the best of both worlds, as you can be both lenient when you're still in the design/prototyping phase of a project, and need to test idea quickly, but also add as much type-check as you see fit when you're maintaining a project, and need to interface with lots of existing code.

As such, I'm always a bit miffed when I see so many people adamant on setting it to maximum strictness by default, under the guise of "best practice".

Re:A 'CSS reset' for TypeScript, improving types for common ... by moogly on Saturday March 04, 2023 @07:49AM (#35020419)
As someone who has "strictified" a lot of code bases after the fact, starting out with `strict` is way less friction than adding it later on.

Especially `strictNullChecks`. It's a massive headache to deal with that later on.

Re:A 'CSS reset' for TypeScript, improving types for common ... by eyelidlessness on Monday March 06, 2023 @03:21PM (#35047031)
Yup. And strict mode tends to guide devs towards better code/API design. Stuff like function/method overloads with dynamic argument types might seem convenient when the types are loosey goosey, but it usually becomes obvious they’re probably a bad idea when you have to specify the types upfront.
Re:A 'CSS reset' for TypeScript, improving types for common ... by capableweb on Friday March 03, 2023 @06:32AM (#35008223)
> Any is okay for 200 LOC quick prototypes

If you're writing a prototype (so the code will eventually be thrown away), it's just 200 LOC and you're using `any` for everything, why even use TypeScript? Should just use vanilla JavaScript instead.

And if you wanna break the rule of throwing away prototype code, you can always "upgrade" it to TypeScript later without too much fuzz.

Re:A 'CSS reset' for TypeScript, improving types for common ... by solarkraft on Friday March 03, 2023 @07:37AM (#35008732)
Standard tooling. It's also still useful even if you just consume the types.
Re:A 'CSS reset' for TypeScript, improving types for common ... by Klathmon on Friday March 03, 2023 @07:38AM (#35008750)
Who said using any for everything?

I love using TS for prototypes because you can define the interfaces wherever you feel they're important, and leave the rest to any.

And like you said, you can always improve the types later

Re:A 'CSS reset' for TypeScript, improving types for common ... by nicoburns on Friday March 03, 2023 @07:48AM (#35008854)
> If you're writing a prototype (so the code will eventually be thrown away), it's just 200 LOC and you're using `any` for everything, why even use TypeScript? Should just use vanilla JavaScript instead.

The case where I've found this useful is making a quick and dirty prototype that integrates within an existing typescript codebase. Such a prototype would never make it to the main branch but sometimes it's useful to make a quick proof of concept of the the runtime behaviour before comitting to sorting out the types.

Re:A 'CSS reset' for TypeScript, improving types for common ... by bazoom42 on Friday March 03, 2023 @09:33AM (#35010097)
‘any’ is great for porting javascript into typescript, and integrating with javascript libraries. You can add types gradually, without everything grinding to a halt.
Re:A 'CSS reset' for TypeScript, improving types for common ... by schwartzworld on Friday March 03, 2023 @09:58AM (#35010407)
Adding types to code that was written with `any` is going to be much harder than using `unknown`.
Re:A 'CSS reset' for TypeScript, improving types for common ... by bazoom42 on Friday March 03, 2023 @10:23AM (#35010785)
The point is if you have existing JavaScript you want to integrate with TypeScript.

You should not need ‘any’ in code written in TypeScript from the beginning.

Re:A 'CSS reset' for TypeScript, improving types for common ... by schwartzworld on Friday March 03, 2023 @10:38AM (#35010972)
Sure, but at least with unknown you will have done some narrowing.

Writing Typescript well requires some fundamentally different patterns than javascript. Adding types afterward is like pulling out your teeth slowly.

Re:A 'CSS reset' for TypeScript, improving types for common ... by 9034725985 on Friday March 03, 2023 @04:03AM (#35007366)
> With the ‘unknown’ type available is there a good case for ‘any’ anymore?

Lets say you have some input json that you want to slightly modify to something else. How would you do this with unknown? I can't just blindly replace any with unknown. I'd get errors like this: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'unknown'.ts(2407) For example, how can I do this better?

Remember the input json could be pretty much anything. I don't have a spec other than I only care about things that end with __c.

https://github.com/kusl/salesforcecontactmapper/blob/eff0b3e...

    import { Output } from "./Output";
    import { Preference } from "./Preference";

    export function MyMap(input: unknown): Output {
        const mypreferences = Array<Preference>();
        for (const prefCode in input) {
            if (prefCode.endsWith("__c")) {
                if (prefCode === "IsInternalUpdate__c") {
                    continue;
                }
                let currentValue = "";
                if (input[prefCode] !== null) {
                    currentValue = input[prefCode].toString();
                }
                if (currentValue === "true") {
                    currentValue = "True";
                }
                if (currentValue === "false") {
                    currentValue = "False";
                }
                const preference: Preference = {
                    PrefCode: prefCode,
                    CurrentValue: currentValue
                }
                mypreferences.push(preference);
            }
        }
        const myOutput: Output = {
            ContactId: input.Contact__c,
            Email: input.ContactEmail__c,
            IsInternalUpdate: true,
            Preferences: mypreferences
        }
        return myOutput;
    }
Re:A 'CSS reset' for TypeScript, improving types for common ... by mxz3000 on Friday March 03, 2023 @04:47AM (#35007636)
well you expect 'input' to be something that you can iterate over, so clearly using any is wrong here.
Re:A 'CSS reset' for TypeScript, improving types for common ... by 9034725985 on Friday March 03, 2023 @05:41AM (#35007951)
yes, input is a json of some kind.

You could say technically could be simply { "Unsubscribe__c": false } or even {} both of which are silly in my case because there is no key for me to identify who the person is but they are valid inputs.

Or the test case I have is https://github.com/kusl/salesforcecontactmapper/blob/eff0b3e...

Or the input could have a thousand key values and I only care about some of them. What should my object look like? How do I create a class that says everything that ends in "__c" is something I care about? I tried unknown. I tried Object. How do I fix this (and learn something so I fix all future code I write)?

Re:A 'CSS reset' for TypeScript, improving types for common ... by erur on Friday March 03, 2023 @05:56AM (#35008036)
You can go incredibly far with the type system.

If you wanna go down that rabbit hole, I'd suggest Typescript type challenges. Completely blew my mind when I came across it the first time.

When you start out with typescript you might think Omit<> and Partial<> are cool but holy hell, you can do so much more.

Re:A 'CSS reset' for TypeScript, improving types for common ... by wizofaus on Friday March 03, 2023 @05:52AM (#35008012)
What's wrong with Object?
Re:A 'CSS reset' for TypeScript, improving types for common ... by 9034725985 on Friday March 03, 2023 @06:25AM (#35008190)
If I set input as Object,

    if (input[prefCode] !== null) {
        currentValue = input[prefCode].toString();
    }
in the lines above, I see a red underline under input[prefCode]

> Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Object'. No index signature with a parameter of type 'string' was found on type 'Object'.ts(7053)

Re:A 'CSS reset' for TypeScript, improving types for common ... by wizofaus on Friday March 03, 2023 @01:59PM (#35013614)
Could you use a helper like

    function getProperty<T, K extends keyof T>(o: T, propertyName: K): T[K] {
        return o[propertyName];
    }

?
Re:A 'CSS reset' for TypeScript, improving types for common ... by sarahdellysse on Friday March 03, 2023 @12:01PM (#35012179)

    input: Record<string, unknown>
Re:A 'CSS reset' for TypeScript, improving types for common ... by 9034725985 on Friday March 03, 2023 @02:27PM (#35013917)
Thank you. That gives me a red underline under ContactId and Email now. I think because input.Contact__c and input.ContactEmail__c are unknown. I think this is the right direction. What is my next step?

    const myOutput: Output = {
        ContactId: input.Contact__c,
        Email: input.ContactEmail__c,
        IsInternalUpdate: true,
        Preferences: mypreferences
    }
(property) Output.ContactId: string Type 'unknown' is not assignable to type 'string'.ts(2322) Output.ts(4, 5): The expected type comes from property 'ContactId' which is declared here on type 'Output'
Re:A 'CSS reset' for TypeScript, improving types for common ... by quickthrower2 on Friday March 03, 2023 @05:57AM (#35008039)
Nice I tbink that is the answer! It is for when the way you need to deal with the data is so dynamic and runtime specified that crafting out the interface/types to cast to would be painful to impossible. Data wrangling.
Re:A 'CSS reset' for TypeScript, improving types for common ... by manhinli on Friday March 03, 2023 @09:30AM (#35010044)
You can do some pretty powerful stuff with TypeScript types, so you could model it like this: https://www.typescriptlang.org/play?#code/C4TwDgpgBAysBOBLAd...
Re:A 'CSS reset' for TypeScript, improving types for common ... by nicoburns on Friday March 03, 2023 @07:46AM (#35008844)
It's can be useful when you're integrating with 3rd party that doesn't support typescript and you just want to say "I don't care about types here". Of course you have to be careful as `any` turns off typing everywhere it appears. But if the usage is local within a function then this may not matter too much.