Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

How to make that one property of an object parameter required and the rest optional in TypeScript?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...