TypeScript error TS2345 All In One
error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
errors
function dailyTemperatures(temperatures: number[]): number[] {
// ❌ error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
let answer = [...``.padEnd(temperatures.length, 0)].map(Number);
// let answer = [...``.padEnd(temperatures.length, 0)].map(i => parseInt(i))!;
// ✅
// let answer = new Array(temperatures.length).fill(0);
let stack: number[] = [];
for(let i = 0; i < temperatures.length; i++) {
while(stack.length && temperatures[stack[stack.length - 1]] < temperatures[i]) {
let index = stack.pop();
answer[index] = i - index;
}
stack.push(i);
}
return answer;
};
https://leetcode.com/problems/daily-temperatures/
https://github.com/SharePoint/sp-dev-training-spfx-webpart-proppane/issues/7#issuecomment-2138695778
solutions
0
=>'0'
, number 替换成 string ✅
function dailyTemperatures(temperatures: number[]): number[] {
// ❌ error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
let answer = [...``.padEnd(temperatures.length, `0`)].map(Number);
// let answer = [...``.padEnd(temperatures.length, 0)].map(Number);
// let answer = [...``.padEnd(temperatures.length, 0)].map(i => parseInt(i))!;
// ✅
// let answer = new Array(temperatures.length).fill(0);
let stack: number[] = [];
for(let i = 0; i < temperatures.length; i++) {
while(stack.length && temperatures[stack[stack.length - 1]] < temperatures[i]) {
let index = stack.pop();
answer[index] = i - index;
}
stack.push(i);
}
return answer;
};
demos
function dailyTemperatures(temperatures: number[]): number[] {
// ❌ error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
let answer = [...``.padEnd(temperatures.length, `0`)].map(Number);
// let answer = [...``.padEnd(temperatures.length, 0)].map(Number);
// let answer = [...``.padEnd(temperatures.length, 0)].map(i => parseInt(i))!;
// ✅
// let answer = new Array(temperatures.length).fill(0);
let stack: number[] = [];
for(let i = 0; i < temperatures.length; i++) {
while(stack.length && temperatures[stack[stack.length - 1]] < temperatures[i]) {
let index = stack.pop();
answer[index] = i - index;
}
stack.push(i);
}
return answer;
};