Hacker News new | ask | show | jobs
by oblak 1198 days ago
Use "unknown" and TS complains that you're treating something as an object.

Use Object.defineProperties and TS complains because that stuff is invisible to it after how many years?

I think you're right, of course, but TS is hardly perfect and treating its ways as gospel is not an improvement over JS. The "right ways" change over time and beliefs are not shared among everyone.

1 comments

If you know what's in the object cast it as that type or be sure by saying if ('propertyName' in unknownObject).

TS is far from perfect. These aren't its ways (it provides any, so of course it's fine with it). These are my restrictions: if you're using a type system, actually use it. Don't lie to yourself and throw anys in your code.

any is the last resort.

How do you get around properties assigned via Object.defineProperties recognised by TS, though? I really don't know. Is is an unrelated question

Here's how I would do it:

    interface IOptionsX {
        x: number;
    }
    
    interface IOptionsY {
        y: number;
    }
    
    const testObj: IOptionsX = {x : 0};
    
    Object.defineProperties(testObj, {
        y: {
            value: 100,
            writable: true
        },
    });
    
    if ('y' in testObj) { // Could also do `&& typeof testObj.y === 'number'` to be VERY sure.
        const testObjWithY = testObj as typeof testObj & IOptionsY;
        console.log(testObjWithY.y)
    }
Though honestly I've gotten this far without EVER using defineProperty so I'd probably continue that streak.