microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
101.13k stars 12.5k forks source link

PositionError does not match docs in MDN #32727

Open tqwewe opened 5 years ago

tqwewe commented 5 years ago

TypeScript Version: 3.5.3

Search Terms: PositionError, Geolocation

Code

const positionError: PositionError = {
    code: 1,
    message: ''
}

Expected behavior: Compiles successfully as this matches the docs here: https://developer.mozilla.org/en-US/docs/Web/API/PositionError

Actual behavior: Type '{ code: number; message: string; }' is missing the following properties from type 'PositionError': PERMISSION_DENIED, POSITION_UNAVAILABLE, TIMEOUT

Playground Link: https://www.typescriptlang.org/play/#code/MYewdgzgLgBADiCBLKTwFEBOmSYFwwAKiKaYWOmMAvDAN4BQMzMoAJgKYECMANEywC2HCBACGAcy4wA5DIYBfBkA

Related Issues: None

IllusionMH commented 5 years ago

Looks like each instance of PositionError should have 3 "static" constants for code comparison. See [PositionError interface definition](http s://www.w3.org/TR/geolocation-API/#position_error_interface)

So in your code you can

function errorCb(error: PositionError) {
    if (error.code === error.PERMISSION_DENIED) {
        console.error('no position info for you');
    }
}

While these constants are in prototype of PositionError instances in runtime, you have to manually create them in your error object otherwise code above will fail.

This is pretty similar to xhr.DONE, xhr.HEADERS_RECEIVED properties on XMLHttpRequest instances.

tqwewe commented 5 years ago

But how should I be creating an instance of PositionError? Can you provide a working example using the code snippet I provided?

IllusionMH commented 5 years ago

As far as I know there is no public constructor for PositionError. If you are using this for test purposes you can just specify all properties required by PositionError interface

Simplest way will be:

const positionError: PositionError = {
    code: 1,
    message: '',
    PERMISSION_DENIED: 1,
    POSITION_UNAVAILABLE: 2,
    TIMEOUT: 3
};

Playground

IllusionMH commented 5 years ago

@RyanCavanaugh if this is Bug with definition, then how properties that are expected to be in objects prototype should be represented in definitions?

I wasn't able to find public constructor for this kind of error, therefore those who implement this interface should provide both sets of properties - from instance and from prototype.

Also same is applicable to XMLHttpRequest (and I think more APIs). Its interface has properties from prototype

readonly DONE: number;
readonly HEADERS_RECEIVED: number;
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;

However

xhr = new XMLHttpRequest()
xhr.hasOwnProperty('DONE') // false
xhr.__proto__.hasOwnProperty('DONE') // true