问题如下
解决办法
StackOverflow Error TS2339: Property 'Connection' does not exist on type 'Navigator'
图示
export type Navigator = NavigatorNetworkInformation
export declare interface NavigatorNetworkInformation {
readonly connection?: NetworkInformation
}
type Megabit = number
type Millisecond = number
export type EffectiveConnectionType = '2g' | '3g' | '4g' | 'slow-2g' | 'unknown'
export type ConnectionType =
| 'bluetooth'
| 'cellular'
| 'ethernet'
| 'mixed'
| 'none'
| 'other'
| 'unknown'
| 'wifi'
| 'wimax'
export interface NetworkInformation extends EventTarget {
readonly type?: ConnectionType
readonly effectiveType?: EffectiveConnectionType
readonly downlinkMax?: Megabit
readonly downlink?: Megabit
readonly rtt?: Millisecond
readonly saveData?: boolean
onchange?: EventListener
}
使用示例
/**
* 取得网络类型
*/
export function getNetworkType() :string {
/* wired 有线
bluetooth,
wifi,
2g,3g,4g,5g...,
unkown
*/
const ua = navigator.userAgent;
const ut = (navigator as Navigator).connection as NetworkInformation;
let utt = ut ? ut.type ? ut.type.toLowerCase() : ut.effectiveType.toLowerCase() : null;
if(utt){
switch (utt) {//bluetooth,
case 'cellular':
case 'wimax':
utt = ut ? ut.effectiveType ? ut.effectiveType.toLowerCase() : null : null;
break;
case 'wifi':
break;
case 'ethernet':
utt = 'wired';
break
case 'none':
case 'other':
case 'unknown':
utt = null;
break
default:
break;
}
}
let networkStr = utt ? utt : ua.match(/NetType\/\w+/) ? ua.match(/NetType\/\w+/)[0] : 'unknown';
networkStr = networkStr.toLowerCase().replace('nettype/', '');
return networkStr ? networkStr === '3gnet' ? '3g' : networkStr : 'unknown';
}