Pete Jones
Pete Jones

Reputation: 21

typescript window.devicePixelRatio

I am trying to use window.devicePixelRatio in a typescript file but this fails to compile with the message "The property 'devicePixelRatio' does not exist on value of type 'Window'"

Is there a fix or must I just use the function outside of typescript?

Pete

Upvotes: 1

Views: 878

Answers (2)

basarat
basarat

Reputation: 275947

I would go with Steve's solution if it works for you. Sometimes visual studio gets quirky and starts to complain variable already defined. Alternately you can always do:

var x = 1;
var win:any = window;

if (win.devicePixelRatio) {
    x = win.devicePixelRatio
}

or

var x = 1;

if ((<any>window).devicePixelRatio) {
    x = (<any>window).devicePixelRatio
}

Upvotes: 3

Fenton
Fenton

Reputation: 250972

You can extend the Window interface with the feature you need - you can do this whenever something new(ish) hasn't made it into lib.d.ts. You may need to remove your extension later on when it does make it into lib.d.ts but the compiler will warn you at that time.

interface Window {
    devicePixelRatio: number;
}

var x = 1;

if (window.devicePixelRatio) {
    x = window.devicePixelRatio
}

Upvotes: 4

Related Questions