Remix.run Logo
nrhrjrjrjtntbt 12 hours ago

Why? why make your code so complex you even hit this problem. Just use the type:

const x: Thetype = ....

I am not keen on as const either. Just program to interfaces. It is a better way to think IMO.

ibejoeb 10 hours ago | parent [-]

The author gets into that. `Thetype` might be complex. It also protects you from overgeneralizing, like casting to and from `unknown` to escape the type checker.

    type Current = {
      kind: "ac" | "dc";
      amps: number;
    }
    
    type Dc = {
      kind: "dc";
      amps: number;
    }
    
    const ac: Current = {
      kind: "ac",
      amps: 10000000,
    }
    
    const handleDc = (thing: Dc) => {}
    
    const badConvert = (c: Current) => ({...c, kind: "dc"});
    
    /**
    * Argument of type '{ kind: string; amps: number; }' is not assignable to parameter of type 'Dc'.
        Types of property 'kind' are incompatible.
            Type 'string' is not assignable to type '"dc"'.(2345)
    */
    handleDc(badConvert(ac));
    
    const goodConvert = (c: Current) => ({
      ...c, kind: "dc",
    } satisfies Dc);
    
    handleDc(goodConvert(ac));
    
    /**
    * Object literal may only specify known properties, and 'bar' does not exist in type 'Dc'.
    */
    const badConvert2 = (c: Current) => ({
      ...c, kind: "dc", bar: "qwerty"
    } satisfies Dc);
another_twist 3 hours ago | parent | next [-]

The bad convert is actually wrong. It should be refactored to an equality check and throw an error if account kind is not "dc". The compiler is correct and its not a good idea to work around this issue.

MrJohz an hour ago | parent [-]

No, the point of the function is to convert the type. It doesn't need to check anything, it just forcibly converts any argument to DC.

The compiler isn't complaining because the conversion isn't valid, it's complaining because it doesn't know that the string "dc" should be narrowed down to a literal type, and so it's kept it as broad as possible. Using `satisfies` lets it understand that it needs to do narrowing here.

In fairness I don't think this is the best case for `satisfies`, and some return type annotations would probably work a lot better here, and be clearer to read.

nrhrjrjrjtntbt 8 hours ago | parent | prev [-]

I see. I dont mind this use case as much. It is like a hint.