Last active
April 29, 2021 17:01
-
-
Save bennettdams/dff407c45dd04a61dababc4a44825bf0 to your computer and use it in GitHub Desktop.
TypeScript: typesafe array filtering for null
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"https://www.typescriptlang.org/play?target=7#code/JYOwLgpgTgZghgYwgAgMJysg3gWAFDLLAAmAXMiAK4C2ARtANz6HUD2xEANuQM5hSgA5sgA+FSp074AvvnwJWIPsgQYAjOXSYxVScgC82ImWRqANMjYduyAEQBBW8ll4FSsCowAmTRlHi9Q10pV0VlVSgAZl9tAM4DIxJySIsrLnJbVCcXeTCPCJ5yAAotf2CASgBtAF0EyojzTygvCwjI6rk8Tgh8jB4AdWAwAAtWSjAAOQkbLRq6jrx8AHol5AB3IeHkADoYYE5ITCLoKFYoDIAVAE8ABxQAcmD7oh4KVg84Hh5gQRA4Wm6yDArCBtweWnu21s5XkfUGIzGk2mCQKu32hyKEQMAD4msgAIT6ILTGGLPArdabHZ7A7QZAAamQHD2ICEoLuyCKw0QAGsrhYeHBqCgbqcARBqMhOMAeShKN8QMJbJ9obCoANNoipoEmjw0bSoEVMRhyuQscBXqV9LisYTiZJykwyRSNiMdlAIMRKEg1RqEeNtfFDKiPV6kAAeWbVbFGxAIVomnGc5gErEAfmQceQ5Eq2zzcYTUAW5QsNVJy1Wrq2u04cDAAFk4DdffDRgHkcG+jW642bsbMNbU34M3McxFqo78EA" | |
interface Car { | |
id: number; | |
model: string | null | |
} | |
const car1: Car | null = { id: 1, model: "A" } | |
const car2: Car | null = null | |
const car3: Car | null = { id: 3, model: "C" } | |
const cars: (Car | null)[] = [car1, car2, car3] | |
let carsWithoutNull: Car[] = [] | |
// with .filter (error: "Type 'null' is not assignable to type 'Car'.") | |
carsWithoutNull = cars.filter(car => car !== null) | |
// with .filter + defining type (hacky, same problem like using "as") | |
carsWithoutNull = cars.filter((car): car is Car => car !== null); | |
// with .reduce | |
carsWithoutNull = cars.reduce<Car[]>((acc, car) => ( | |
!car ? acc : [...acc, car] | |
), []) | |
// with .flatMap | |
carsWithoutNull = cars.flatMap(car => !car ? [] : [car]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment