Hur man ser om en filtrerad array av objekt i Typescript innehåller en nyckel?
I följande kod:
interface Obj {
requiredKey: string;
optionalKey?: string;
}
type Arr = Array<Obj>;
const arr: Arr = [
{
requiredKey: "a",
optionalKey: "b",
},
{
requiredKey: "c",
},
];
const filtered = arr.filter((obj) => obj.optionalKey);
Hur säger jag till TS att filtered innehåller objekt där optionalKey finns? Det betyder att typen nu är:
{
requiredKey: string;
optionalKey: string;
}[]
Svar #1
Vi kan modifiera Robbys svar något, så att det fungerar utan att hårdkoda Obj-typen inuti filter och också utan att av misstag göra orelaterade egenskaper obligatoriska.
const filtered = arr.filter(
(obj): obj is typeof obj & { optionalKey: string } =>
typeof obj.optionalKey === 'string'
);
Lekplats
Svar #2
Du kan använda Required-nyttotypen med en användardefinierad typvakt:
interface Obj {
requiredKey: string;
optionalKey?: string;
}
const arr: Array<Obj> = [
{
requiredKey: "a",
optionalKey: "b",
},
{
requiredKey: "c",
},
];
const filtered = arr.filter(
(obj): obj is Required<Obj> => typeof obj.optionalKey === 'string'
);
