Getting Started
platform-ts
is a synchronous, type-safe utility for user-agent sniffing. You can get it by running:
bashnpm i platform-ts
Usage
This module uses discriminated unions to represent the distinction between common, known browsers, engines, devices, and operating systems. The following example shows the structure of the Browser
type:
typescriptexport interface UnknownBrowser {
name: null;
originalName?: string;
version?: string;
known: false;
}
export interface KnownBrowser {
name: KnownBrowserNames;
originalName: string;
version?: string;
known: true;
}
export type Browser = UnknownBrowser | KnownBrowser;
We can use this type to determine the user's browser with type inference. The following example shows how to use the Browser
type to determine the user's browser:
typescriptimport { PlatformReader } from "platform-ts";
const platform = new PlatformReader();
const browser = platform.getBrowser();
if (browser.known) {
// browser name can be autocompleted here
// one of the `KnownBrowserNames` is available
console.log(browser.name);
} else {
// browser name is unknown
// `name` is null, but `originalName` is available
// if the user agent string is parsable
console.log(browser.originalName);
}