Czemu nie działa mi ta składnia w ts, gdy chce użyć metody filter? Chciałbym dodać typ do ages.
const ages = [32, 33, 16, 40];
const result = (ages: Array<number>).filter(checkAdult));
function checkAdult(age) {
return age >= 18;
}
Czemu nie działa mi ta składnia w ts, gdy chce użyć metody filter? Chciałbym dodać typ do ages.
const ages = [32, 33, 16, 40];
const result = (ages: Array<number>).filter(checkAdult));
function checkAdult(age) {
return age >= 18;
}
A co ci nie działa? Jaki masz błąd?
Update:
to mi działa
const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age: number) {
return age >= 18;
}
KamilAdam napisał(a):
A co ci nie działa? Jaki masz błąd?
Update:
to mi działaconst ages = [32, 33, 16, 40]; const result = ages.filter(checkAdult); function checkAdult(age: number) { return age >= 18; }
Wiem, że w taki sposób zadziała. Ja natomiast chce dodać typ do ages. Wtedy mam taki błąd: "Expected '=>', got '.'"
No to
const ages : number[] = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age: number) {
return age >= 18;
}
KamilAdam napisał(a):
No to
const ages : number[] = [32, 33, 16, 40]; const result = ages.filter(checkAdult); function checkAdult(age: number) { return age >= 18; }
Tak wiem, że tak można zrobić. Tylko ja chce dodać ten typ w drugiej linijce. Czy nie ma takiej możliwości żeby w 2 linijce dodać typ i dobrze to działało?
To może zrzutuj każdy element z osobna?
const ages = [32, 33, 16, 40];
const result = ages.map(a => a as number).filter(checkAdult);
function checkAdult(age: number) {
return age >= 18;
}
?
UPDATE: Mam, chyba wpiszę sobie TSa do CV :D
const ages = [32, 33, 16, 40];
const result = (ages as number[]).filter(checkAdult);
function checkAdult(age: number) {
return age >= 18;
}
BTW wydaje się jakby składnia z as
potrafiła więcej niż składnia z <>
, ciekawe
A ludzie się dziwią, kiedy mówię, że TypeScript więcej generuje problemów, niż rozwiązuje :D
Po co chcesz dodać typ do ages?
Z tego, co widzę, to TS już sam dodaje i możesz napisać tak:
const ages = [32, 33, 16, 40];
const adults = ages.filter(age => age >= 18);
zauważ, że to już jest prawdziwy TypeScript. Działa inferencja typów. I np. po zmianie na
const adults = ages.filter(age => age >= "foo");
pokazuje się błąd: Operator '>=' cannot be applied to types 'number' and 'string'
Ale jakbyś chciał faktycznie przypisać explicite typ, to czemu nie zrobisz po prostu tak:
const ages: Array<number> = [32, 33, 16, 40];
?