打字稿错误:无法将类型“ T”的参数分配给类型“ number”的参数?

时间:2019-08-14 06:58:02

标签: angular typescript angular8

有人可以告诉我这里打字错误吗?

//差を求める日時の変数を作成
$dateTime1 = '2010-04-01';
$dateTime2 = '2019-06-30';

//DateTimeクラスで2つの日時のオブジェクトを作成
$objDatetime1 = new DateTime($dateTime1);
$objDatetime2 = new DateTime($dateTime2);

//diff()メソッドで2つの日時のオブジェクトから
//ふたつの日付の差をあらわす DateInterval オブジェクトを生成する
$objInterval = $objDatetime1->diff($objDatetime2);

//$objInterval(DateInterval オブジェクト)をformat()メソッドで日時を出力
//%Rは + や - の符号を出力するオプションです
echo $objInterval->format('%R%Y').'year<br/>'; //年
echo $objInterval->format('%R%M').'month<br/>'; //月
echo $objInterval->format('%R%D').'day<br/>'; //日
?>
  

isNaN(a)    和> isNaN(b)引发以下错误。

public sortList<T>(data: T[], key: string, action: boolean): Observable<T[]> {

const outputData: T[] =  data.sort((a, b) => {
  if (isNaN(a) && isNaN(b)) {
    return a[key].toUpperCase() > b[key].toUpperCase() ? 1 : a[key].toUpperCase() < b[key].toUpperCase() ? -1 : 0;
  }
});

return of(outputData)
  .pipe(
    share()
  );
}
}

1 个答案:

答案 0 :(得分:1)

不鼓励使用isNaN的杂乱版本,尽管我可以看到您正在使用它来检查类型和NaN。尽管这有点麻烦,但最好多花些功夫,并使用类型检查来检查类型,并使用NaN检查来检查NaN

控制台日志的第一块(1-3)向您显示您从isNaN开始使用的行为。我将在下一部分(4-6)中使用类型检查的(倒置)等效项。

最后一位(7-8)显示类型和NaN检查的用法。在此阶段,您不依赖于isNaN的粗略行为,可以使用全局版本(现在确定使用的是数字)或Number.isNaN版本,该版本更严格

带括号的版本没有编译器警告。

const num = 1;
const str = 'string';
const obj = { key: 'value' };

// Technically works, but compiler warnings

console.log('1.', isNaN(num)); // false
console.log('2.', isNaN(str)); // true
console.log('3.', isNaN(obj)); // true

// A bit more type-ish (note the results are inverted as I'm showing the "positive" test

console.log('4.', typeof num === 'number'); // true
console.log('5.', typeof str === 'number'); // false
console.log('6.', typeof obj === 'number'); // false

const a = 1;

if (typeof a === 'number') {
    console.log('7a.', isNaN(a)); // false
    console.log('7b.', Number.isNaN(a)); // false
}

const b = NaN;

if (typeof b === 'number') {
    console.log('8a.', isNaN(b)); // true
    console.log('8b.', Number.isNaN(b)); // true
}

这是从数字中筛选出字符串的版本:

function stringNumberCheck(strNum: string | number) : boolean {
    const numeric = +strNum;
    return (typeof numeric === 'number' && !Number.isNaN(numeric));
}

console.log('1:', stringNumberCheck(1)); // true
console.log("'100':", stringNumberCheck('100')); // true
console.log("'Hello':", stringNumberCheck('Hello')); // false

演示

"use strict";
function stringNumberCheck(strNum) {
    const numeric = +strNum;
    return (typeof numeric === 'number' && !Number.isNaN(numeric));
}
console.log('1:', stringNumberCheck(1)); // true
console.log("'100':", stringNumberCheck('100')); // true
console.log("'Hello':", stringNumberCheck('Hello')); // false

相关问题