Return an object without certain keys (dynamic, typesafe)2019 Community Moderator ElectionTyping removal of a key from an objectHow do I dynamically assign properties to an object in TypeScript?access key and value of object using *ngForng-if/ng-hide doesn't get updated on real time on HTML pageboolean set to false; returns true on if statement without ==Return boolean (true | false) value when all delete operations are successfully performedTypescript boolean function must return a valueWhat would the type definition look like for a function that returns an object that is a subset of an original objecthow can you express “keyof T” to be a subset of String?Trying to use map() in TypeScript with a get-or-default statementIf statement is not working when I pass a Boolean variable to a function?

Vector-transposing function

I am the person who abides by rules but breaks the rules . Who am I

How can I portion out frozen cookie dough?

Was this cameo in Captain Marvel computer generated?

Unfamiliar notation in Diabelli's "Duet in D" for piano

3.5% Interest Student Loan or use all of my savings on Tuition?

Sort array by month and year

Interpretation of linear regression interaction term plot

How would an energy-based "projectile" blow up a spaceship?

What do you call someone who likes to pick fights?

How to educate team mate to take screenshots for bugs with out unwanted stuff

School performs periodic password audits. Is my password compromised?

Mixed Feelings - What am I

How spaceships determine each other's mass in space?

Can I challenge the interviewer to give me a proper technical feedback?

Did Amazon pay $0 in taxes last year?

Why isn't P and P/poly trivially the same?

Does the US political system, in principle, allow for a no-party system?

Issue with units for a rocket nozzle throat area problem

Averaging over columns while ignoring zero entries

How can I have x-axis ticks that show ticks scaled in powers of ten?

If nine coins are tossed, what is the probability that the number of heads is even?

What is better: yes / no radio, or simple checkbox?

Use Mercury as quenching liquid for swords?



Return an object without certain keys (dynamic, typesafe)



2019 Community Moderator ElectionTyping removal of a key from an objectHow do I dynamically assign properties to an object in TypeScript?access key and value of object using *ngForng-if/ng-hide doesn't get updated on real time on HTML pageboolean set to false; returns true on if statement without ==Return boolean (true | false) value when all delete operations are successfully performedTypescript boolean function must return a valueWhat would the type definition look like for a function that returns an object that is a subset of an original objecthow can you express “keyof T” to be a subset of String?Trying to use map() in TypeScript with a get-or-default statementIf statement is not working when I pass a Boolean variable to a function?










1















I'm trying to implement a "except"-method in TypeScript.
The purpose would be something like this:



const obj = a: true, b: 1, c: 'test', d: false 
const objExcept = except(obj, 'b', 'd')


My problem is not the actual key exclusion, but the typesafe return value.
Ideally accessing objExcept.b should give me an error, cause the return value is:



objExcept: a: boolean, c: string = a: true, c: 'test' `


This is my current implementation



export function except<
T extends Dictionary,
K extends any[],
R extends Pick<T, Exclude<keyof T, K[number]>>
> (value: T, ...exceptions: K): R
const copy: Record<string: any> =
for (const key in value)
if (!value.hasOwnProperty(key)

return copy as R



Many thanks in advance










share|improve this question






















  • I asked something slightly similar a while ago, does it help at all?: stackoverflow.com/questions/54199582/…

    – OliverRadini
    2 days ago











  • @OliverRadini forgot I answered that :))

    – Titian Cernicova-Dragomir
    2 days ago






  • 1





    @TitianCernicova-Dragomir haha I was wondering if you'd answer this one, your answer to my question was very useful!

    – OliverRadini
    2 days ago






  • 1





    Thanks for the hint @OliverRadini. The problem is quite similar but for my purpose i had to be able to exclude 1+ keys

    – skillmotion
    2 days ago















1















I'm trying to implement a "except"-method in TypeScript.
The purpose would be something like this:



const obj = a: true, b: 1, c: 'test', d: false 
const objExcept = except(obj, 'b', 'd')


My problem is not the actual key exclusion, but the typesafe return value.
Ideally accessing objExcept.b should give me an error, cause the return value is:



objExcept: a: boolean, c: string = a: true, c: 'test' `


This is my current implementation



export function except<
T extends Dictionary,
K extends any[],
R extends Pick<T, Exclude<keyof T, K[number]>>
> (value: T, ...exceptions: K): R
const copy: Record<string: any> =
for (const key in value)
if (!value.hasOwnProperty(key)

return copy as R



Many thanks in advance










share|improve this question






















  • I asked something slightly similar a while ago, does it help at all?: stackoverflow.com/questions/54199582/…

    – OliverRadini
    2 days ago











  • @OliverRadini forgot I answered that :))

    – Titian Cernicova-Dragomir
    2 days ago






  • 1





    @TitianCernicova-Dragomir haha I was wondering if you'd answer this one, your answer to my question was very useful!

    – OliverRadini
    2 days ago






  • 1





    Thanks for the hint @OliverRadini. The problem is quite similar but for my purpose i had to be able to exclude 1+ keys

    – skillmotion
    2 days ago













1












1








1








I'm trying to implement a "except"-method in TypeScript.
The purpose would be something like this:



const obj = a: true, b: 1, c: 'test', d: false 
const objExcept = except(obj, 'b', 'd')


My problem is not the actual key exclusion, but the typesafe return value.
Ideally accessing objExcept.b should give me an error, cause the return value is:



objExcept: a: boolean, c: string = a: true, c: 'test' `


This is my current implementation



export function except<
T extends Dictionary,
K extends any[],
R extends Pick<T, Exclude<keyof T, K[number]>>
> (value: T, ...exceptions: K): R
const copy: Record<string: any> =
for (const key in value)
if (!value.hasOwnProperty(key)

return copy as R



Many thanks in advance










share|improve this question














I'm trying to implement a "except"-method in TypeScript.
The purpose would be something like this:



const obj = a: true, b: 1, c: 'test', d: false 
const objExcept = except(obj, 'b', 'd')


My problem is not the actual key exclusion, but the typesafe return value.
Ideally accessing objExcept.b should give me an error, cause the return value is:



objExcept: a: boolean, c: string = a: true, c: 'test' `


This is my current implementation



export function except<
T extends Dictionary,
K extends any[],
R extends Pick<T, Exclude<keyof T, K[number]>>
> (value: T, ...exceptions: K): R
const copy: Record<string: any> =
for (const key in value)
if (!value.hasOwnProperty(key)

return copy as R



Many thanks in advance







typescript






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 2 days ago









skillmotionskillmotion

153




153












  • I asked something slightly similar a while ago, does it help at all?: stackoverflow.com/questions/54199582/…

    – OliverRadini
    2 days ago











  • @OliverRadini forgot I answered that :))

    – Titian Cernicova-Dragomir
    2 days ago






  • 1





    @TitianCernicova-Dragomir haha I was wondering if you'd answer this one, your answer to my question was very useful!

    – OliverRadini
    2 days ago






  • 1





    Thanks for the hint @OliverRadini. The problem is quite similar but for my purpose i had to be able to exclude 1+ keys

    – skillmotion
    2 days ago

















  • I asked something slightly similar a while ago, does it help at all?: stackoverflow.com/questions/54199582/…

    – OliverRadini
    2 days ago











  • @OliverRadini forgot I answered that :))

    – Titian Cernicova-Dragomir
    2 days ago






  • 1





    @TitianCernicova-Dragomir haha I was wondering if you'd answer this one, your answer to my question was very useful!

    – OliverRadini
    2 days ago






  • 1





    Thanks for the hint @OliverRadini. The problem is quite similar but for my purpose i had to be able to exclude 1+ keys

    – skillmotion
    2 days ago
















I asked something slightly similar a while ago, does it help at all?: stackoverflow.com/questions/54199582/…

– OliverRadini
2 days ago





I asked something slightly similar a while ago, does it help at all?: stackoverflow.com/questions/54199582/…

– OliverRadini
2 days ago













@OliverRadini forgot I answered that :))

– Titian Cernicova-Dragomir
2 days ago





@OliverRadini forgot I answered that :))

– Titian Cernicova-Dragomir
2 days ago




1




1





@TitianCernicova-Dragomir haha I was wondering if you'd answer this one, your answer to my question was very useful!

– OliverRadini
2 days ago





@TitianCernicova-Dragomir haha I was wondering if you'd answer this one, your answer to my question was very useful!

– OliverRadini
2 days ago




1




1





Thanks for the hint @OliverRadini. The problem is quite similar but for my purpose i had to be able to exclude 1+ keys

– skillmotion
2 days ago





Thanks for the hint @OliverRadini. The problem is quite similar but for my purpose i had to be able to exclude 1+ keys

– skillmotion
2 days ago












1 Answer
1






active

oldest

votes


















2














You are very close you just need to get the compiler to infer literal types for K. The best way to do this is to restrict the items in K to keyof T. This will also check that property keys are part of the target object.



export function except<
T extends Record<string, any>,
K extends Array<keyof T>,
R extends Pick<T, Exclude<keyof T, K[number]>>
> (value: T, ...exceptions: K): R
const copy: Record<string, any> =
for (const key in value)
if (!value.hasOwnProperty(key)

return copy as R


const obj = a: true, b: 1, c: 'test', d: false
const objExcept = except(obj, 'b', 'd')
objExcept.a
objExcept.b //err


If you want to allow any keys not necessarily just known keys of T you can also use K extends Array<PropertyKey> this will allow any key but exclude any keys that overlap from T






share|improve this answer























  • Thank you so much (actually: again ;)). I work's perfectly fine now

    – skillmotion
    2 days ago










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55023523%2freturn-an-object-without-certain-keys-dynamic-typesafe%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














You are very close you just need to get the compiler to infer literal types for K. The best way to do this is to restrict the items in K to keyof T. This will also check that property keys are part of the target object.



export function except<
T extends Record<string, any>,
K extends Array<keyof T>,
R extends Pick<T, Exclude<keyof T, K[number]>>
> (value: T, ...exceptions: K): R
const copy: Record<string, any> =
for (const key in value)
if (!value.hasOwnProperty(key)

return copy as R


const obj = a: true, b: 1, c: 'test', d: false
const objExcept = except(obj, 'b', 'd')
objExcept.a
objExcept.b //err


If you want to allow any keys not necessarily just known keys of T you can also use K extends Array<PropertyKey> this will allow any key but exclude any keys that overlap from T






share|improve this answer























  • Thank you so much (actually: again ;)). I work's perfectly fine now

    – skillmotion
    2 days ago















2














You are very close you just need to get the compiler to infer literal types for K. The best way to do this is to restrict the items in K to keyof T. This will also check that property keys are part of the target object.



export function except<
T extends Record<string, any>,
K extends Array<keyof T>,
R extends Pick<T, Exclude<keyof T, K[number]>>
> (value: T, ...exceptions: K): R
const copy: Record<string, any> =
for (const key in value)
if (!value.hasOwnProperty(key)

return copy as R


const obj = a: true, b: 1, c: 'test', d: false
const objExcept = except(obj, 'b', 'd')
objExcept.a
objExcept.b //err


If you want to allow any keys not necessarily just known keys of T you can also use K extends Array<PropertyKey> this will allow any key but exclude any keys that overlap from T






share|improve this answer























  • Thank you so much (actually: again ;)). I work's perfectly fine now

    – skillmotion
    2 days ago













2












2








2







You are very close you just need to get the compiler to infer literal types for K. The best way to do this is to restrict the items in K to keyof T. This will also check that property keys are part of the target object.



export function except<
T extends Record<string, any>,
K extends Array<keyof T>,
R extends Pick<T, Exclude<keyof T, K[number]>>
> (value: T, ...exceptions: K): R
const copy: Record<string, any> =
for (const key in value)
if (!value.hasOwnProperty(key)

return copy as R


const obj = a: true, b: 1, c: 'test', d: false
const objExcept = except(obj, 'b', 'd')
objExcept.a
objExcept.b //err


If you want to allow any keys not necessarily just known keys of T you can also use K extends Array<PropertyKey> this will allow any key but exclude any keys that overlap from T






share|improve this answer













You are very close you just need to get the compiler to infer literal types for K. The best way to do this is to restrict the items in K to keyof T. This will also check that property keys are part of the target object.



export function except<
T extends Record<string, any>,
K extends Array<keyof T>,
R extends Pick<T, Exclude<keyof T, K[number]>>
> (value: T, ...exceptions: K): R
const copy: Record<string, any> =
for (const key in value)
if (!value.hasOwnProperty(key)

return copy as R


const obj = a: true, b: 1, c: 'test', d: false
const objExcept = except(obj, 'b', 'd')
objExcept.a
objExcept.b //err


If you want to allow any keys not necessarily just known keys of T you can also use K extends Array<PropertyKey> this will allow any key but exclude any keys that overlap from T







share|improve this answer












share|improve this answer



share|improve this answer










answered 2 days ago









Titian Cernicova-DragomirTitian Cernicova-Dragomir

69.2k34765




69.2k34765












  • Thank you so much (actually: again ;)). I work's perfectly fine now

    – skillmotion
    2 days ago

















  • Thank you so much (actually: again ;)). I work's perfectly fine now

    – skillmotion
    2 days ago
















Thank you so much (actually: again ;)). I work's perfectly fine now

– skillmotion
2 days ago





Thank you so much (actually: again ;)). I work's perfectly fine now

– skillmotion
2 days ago



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55023523%2freturn-an-object-without-certain-keys-dynamic-typesafe%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved