我正在尝试添加以下代码来检测浏览器,但是我遇到的browserData
错误是:
Type '{ browserName: () => string; browserVersion: string | null; operatingSystem: string | (() => string); } | { browserName: string; browserVersion: string; operatingSystem: string; }' is not assignable to type 'BrowserData'.
Type '{ browserName: () => string; browserVersion: string | null; operatingSystem: string | (() => string); }' is not assignable to type 'BrowserData'.
Types of property 'browserName' are incompatible.
Type '() => string' is not assignable to type 'string'.ts(2322)
function getBrowserInfo(): BrowserData {
const browserInfo = detectBrowser.detect();
const browserData: BrowserData =
browserInfo !== null
? {
browserName: browserInfo.name.toString,
browserVersion: browserInfo.version,
operatingSystem:
browserInfo.os !== null ? browserInfo.os.toString : '',
}
: { browserName: '', browserVersion: '', operatingSystem: '' };
return browserData;
}
declare type BrowserData = {
browserName: string;
browserVersion: string;
operatingSystem: string;
};
我看到有一个错误,因为返回值应该是一个字符串,而不是返回字符串的函数。我该如何纠正?
答案 0 :(得分:1)
您需要调用toString
方法-否则,您正在使browserName
和可能的operatingSystem
一个函数:
function getBrowserInfo(): BrowserData {
const browserInfo = detectBrowser.detect();
const browserData: BrowserData =
browserInfo !== null ?
{
browserName: browserInfo.name.toString(),
browserVersion: browserInfo.version,
operatingSystem: browserInfo.os !== null ? browserInfo.os.toString() : '',
} :
{
browserName: '',
browserVersion: '',
operatingSystem: ''
};
return browserData;
}