Use a type
or an interface
, then declare optional properties (using ?
).
Using a type
:
type Sweets = {
candy?: string;
chocolate: string;
lollipop?: string;
}
Using an interface
:
interface Sweets {
candy?: string;
chocolate: string;
lollipop?: string;
}
And then in your script:
const sweets: Sweets = {
candy: 'Skittles',
chocolate: 'Milka',
lollipop: 'ChupaChups',
};
const getChocolate = ({ chocolate }: Sweets): boolean => chocolate.includes('something');
Update to define type on function instead of on argument
You can use a generic
type on your function to dynamically-type the function's argument. I believe something like this should do what you want:
/*
'T' is a generic type, you can set the type
when you _call_ the function,
not when you define it
extending Record<'chocolate', string> means that
although we don't know the argument type yet,
we know it should at least have a chocolate: string property
*/
const getChocolate = <T extends Record<'chocolate', string>>(
{ chocolate }: T,
): boolean => chocolate.includes('something');
// the type for arg `{ chocolate }` will be set when the function is _called_
// argument for `{ chocolate }` is now of type 'Sweets'
getChocolate<Sweets>(mySweets);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…