我尝试添加以下代码来检测浏览器,但 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;
};
我发现存在错误,因为返回值应该是字符串,而不是返回字符串的函数。我该如何纠正这个问题?
最佳答案
您需要调用 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;
}
关于javascript - Typescript - 函数应该返回一个字符串而不是 () -> 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55735941/