Giter Club home page Giter Club logo

Comments (13)

jcalz avatar jcalz commented on September 27, 2024 2

TS is working as designed and you've run into a known inconsistency/unsoundness in the language.

#12936: object types in TS are not "exact" (e.g., the objects you don't like are both valid Foo objects)
#20863: excess property checks don't occur for non-discriminated unions
#34975: the in operator is intentionally unsound

from typescript.

MartinJohns avatar MartinJohns commented on September 27, 2024 2

both objects are Foo with a bar and zaz excess property respectively?

That's correct. And excess property checks don't kick in as per #20863 (linked by jcalz already).

In that case, isn't it the narrowing that cannot be trusted since it shouldn't allow you to narrow it down to Bar in the function declaration since it could be Foo with an excess property?

jcalz already linked the relevant issue here too: #34975. The in operator is intentionally unsound. You either accept this, or check the entire structure of your object, or (IMO the best option) add a discriminator property to your types.

Ideally, I'd like user to specify one object or the other when calling the function and have it fail if it doesn't have all the properties of one of the objects. Is that even possible?

That's... how it works with the code you have already.

from typescript.

jcalz avatar jcalz commented on September 27, 2024 1

#12936 (comment)

from typescript.

MartinJohns avatar MartinJohns commented on September 27, 2024 1

There is #55143.

from typescript.

jcalz avatar jcalz commented on September 27, 2024 1

@MartinJohns I think we've had this disagreement before about things like {bar?: never}. If the possibility of a getter that throws is something to worry about then you always have to worry about it because every type T is equivalent to T | never. I would just check typeof props.bar !== "undefined" (instead of using in, which I agree isn't the right check) and if it blows up there then I'm fine, right?

from typescript.

MartinJohns avatar MartinJohns commented on September 27, 2024

See also the FAQ:
(Indirect) Excess Properties Are OK
What is structural typing?

from typescript.

davidbarratt avatar davidbarratt commented on September 27, 2024

@MartinJohns

If I'm understanding that correctly in these two failing cases:

baz({ foo: "test", bar: 123 }); // undefined
baz({ foo: "test", zaz: "dsfdf1" }); // test

both objects are Foo with a bar and zaz excess property respectively?

In that case, isn't it the narrowing that cannot be trusted since it shouldn't allow you to narrow it down to Bar in the function declaration since it could be Foo with an excess property?

In which case the only way to narrow it would be to eliminate Foo?

interface Foo {
    foo: string;
    jaz: number;
}

interface Bar {
    bar: number;
    zaz: string;
}

function baz(props: Foo | Bar ) {
    if (!("foo" in props)) {
        console.log(props.zaz);
    }
    else {
        console.log(props.jaz);
    }
}

baz({ bar: 123, jaz: 1234, foo: "blah" }); // 1234

Ideally, I'd like user to specify one object or the other when calling the function and have it fail if it doesn't have all the properties of one of the objects. Is that even possible?

from typescript.

davidbarratt avatar davidbarratt commented on September 27, 2024

I think I found a solution:

interface Foo {
    foo: string;
    zaz?: never;
    bar?: never;
}

interface Bar {
    foo?: never;
    bar: number;
    zaz: string;
}

function baz(props: Foo | Bar ) {
    if ("bar" in props) {
        console.log(props.zaz);
    } else {
        console.log(props.foo);
    }
}

baz({ foo: "test" }); // test
baz({ bar: 1234, zaz: "yuh" }); // yuh

// oops! you can pass a subset of "both" rather than "one or the other".

baz({ foo: "test", bar: 123 }); //  FAILS
baz({ foo: "test", zaz: "dsfdf1" }); // FAILS

https://www.typescriptlang.org/play/?exactOptionalPropertyTypes=true&ts=5.5.4&ssl=27&ssc=45&pln=1&pc=1#code/JYOwLgpgTgZghgYwgAgGIHt3IN4ChkHIyYBcyAzmFKAOYDc+hAXnEwPxkgQBu0DhyAEZwoHZF15QGAX1y5QkWIhQAhETkYFi6MRL6ahIzgFcAtoP0CWTMpWoh6uWbhjGQCMMHQhDTABQADlDoAeRkGFgAPshqUMgAlBoCwDDIfgBEwlDpyKDIQSHkiXgCAgje5OgANhAAdFXoNIHBobXW8fyE0sgQVeQoJaUE5SCVNfWNzYW12h0Gss7C-thEpMjpkJQ50h3IAPR7yJtguEt+K1lkAIwATADMACwANMjWZOkAnsYAFtu7B8gvt85ADMKEAISA9DGZAIOA+AJwcjkZBwCjGQT9MDIdCpTLoMC-ZBQOCE6BHb7w9beFDoOJknFk7K1ORnFbad7HdIvS7IW53ZA7Oj7Q5uAAmEBgoAgYtOrHOq3QnIgWxeb3WYvIMDFMCuf2FAOOQA

It might be helpful if the docs were updated with something like that. Like you can make your unions safer by specifying all the known properties of the other values.

from typescript.

MartinJohns avatar MartinJohns commented on September 27, 2024

I wouldn't call this a "solution", but rather a crude workaround / hack. This call is still legit and will blow up:

baz({ foo: "test", get bar(): never { throw 1 } , get zaz(): never { throw 1 } });

A property typed never does not mean the property doesn't exist..

from typescript.

davidbarratt avatar davidbarratt commented on September 27, 2024

@MartinJohns Is there an issue for having a syntax for "property does not exist" ? That seems like less of a lift than #12936 right?

from typescript.

davidbarratt avatar davidbarratt commented on September 27, 2024

FWIW I find it rather unintuitive that Excess Property Checks occur, but not if the property just so happens to be part of another object in the union.

Take for instance this execution:

baz({ foo: "test", bar: 123 }); // undefined
baz({ foo: "test", saz: "test" }); // FAIL

https://www.typescriptlang.org/play/?exactOptionalPropertyTypes=true&ts=5.5.4#code/JYOwLgpgTgZghgYwgAgGIHt3IN4ChkHIyYBcyAzmFKAOYDcuAvrrqJLIigEJxQ76EARrzIgArgFtB0BoWQAvOPLKVqIekxYwxIBGGDoQyYfIAUAByjpz5MhiwAfZDz4BKfnOAxkpgETCoX2RQZEtrcnc8OTkEQ3J0ABsIADoE9BoLKxtkxXlXWUJGZAgE8hQo6IJYkHik1PTM8OTidHyBAmZmXBNTbCJSZF9ISiDGfOQAegnkYbBupV7jEWQARgAmAGYAFgAaBSUyXwBPMQALUfGp5BPTliuAYXQoKAhwBKO0OGBS+bM+lsOs18e3IB1Wm2QYzok2mqAAggBJAAyAGU7tNMDYAITXdBiZAIOBGcxwcjkZBwChiQRlMDIdDefzoMDnZBQOAs6AzU5EwaGFBPbkCzmBZIsHr-AZDCAjPYBMjrDaQy7THQAEwgMFAEDVv0WAMGQL2uUOavIMDVMBWF2hV1mQA

Why is it that excess checks just get disabled if the property happens to be bar? Clearly it's an excess property of Foo and TypeScript knows that and does it correctly when it's a different property name.

from typescript.

jcalz avatar jcalz commented on September 27, 2024

looks meaningfully at #20863

from typescript.

davidbarratt avatar davidbarratt commented on September 27, 2024

@jcalz I see, this is the same issue. My apologies, I was tripped up by some of the language used in the issue. Thank you for your help!

from typescript.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.