How can I specify that Typescript generic T[K] is number type?Create instance of generic type in Java?How do I use reflection to call a generic method?How to create a generic array in Java?How to get the type of T from a member of a generic class or method?How to get a class instance of generics type TAre strongly-typed functions as parameters possible in TypeScript?TypeScript Converting a String to a numberTypescript: Interfaces vs TypesTypeScript compile error TS2322 when assigning a value of a generic typeTypescript clarification on index types and mapped types

Everything Bob says is false. How does he get people to trust him?

Hostile work environment after whistle-blowing on coworker and our boss. What do I do?

Tiptoe or tiphoof? Adjusting words to better fit fantasy races

Print name if parameter passed to function

apt-get update is failing in debian

What will be the benefits of Brexit?

What's a natural way to say that someone works somewhere (for a job)?

voltage of sounds of mp3files

The baby cries all morning

Opposite of a diet

How to verify if g is a generator for p?

Irreducibility of a simple polynomial

Generic lambda vs generic function give different behaviour

How will losing mobility of one hand affect my career as a programmer?

How do I define a right arrow with bar in LaTeX?

Why is delta-v is the most useful quantity for planning space travel?

Go Pregnant or Go Home

Is a roofing delivery truck likely to crack my driveway slab?

Using parameter substitution on a Bash array

What defines a dissertation?

Cynical novel that describes an America ruled by the media, arms manufacturers, and ethnic figureheads

Star/Wye electrical connection math symbol

Greatest common substring

Can criminal fraud exist without damages?



How can I specify that Typescript generic T[K] is number type?


Create instance of generic type in Java?How do I use reflection to call a generic method?How to create a generic array in Java?How to get the type of T from a member of a generic class or method?How to get a class instance of generics type TAre strongly-typed functions as parameters possible in TypeScript?TypeScript Converting a String to a numberTypescript: Interfaces vs TypesTypeScript compile error TS2322 when assigning a value of a generic typeTypescript clarification on index types and mapped types













1















I have a simple Typescript function like this:



function getProperty<T, K extends keyof T>(obj: T, key: K): number 
return obj[key]; // This line is not compiling.
// Typescript will yell: "Type 'T[K]' is not assignable to type 'number'."



My usage looks like this:



const someObj = 
myValue: 123,
otherProperty: '321'


getProperty(someObj, 'myValue')


I won't know what structure of someObj will be.



My question is: How can I specify that T[K] is number type statically?










share|improve this question



















  • 1





    @T.J.Crowder I've updated my use case, thank you!

    – Joseph Wang
    Mar 8 at 9:51















1















I have a simple Typescript function like this:



function getProperty<T, K extends keyof T>(obj: T, key: K): number 
return obj[key]; // This line is not compiling.
// Typescript will yell: "Type 'T[K]' is not assignable to type 'number'."



My usage looks like this:



const someObj = 
myValue: 123,
otherProperty: '321'


getProperty(someObj, 'myValue')


I won't know what structure of someObj will be.



My question is: How can I specify that T[K] is number type statically?










share|improve this question



















  • 1





    @T.J.Crowder I've updated my use case, thank you!

    – Joseph Wang
    Mar 8 at 9:51













1












1








1








I have a simple Typescript function like this:



function getProperty<T, K extends keyof T>(obj: T, key: K): number 
return obj[key]; // This line is not compiling.
// Typescript will yell: "Type 'T[K]' is not assignable to type 'number'."



My usage looks like this:



const someObj = 
myValue: 123,
otherProperty: '321'


getProperty(someObj, 'myValue')


I won't know what structure of someObj will be.



My question is: How can I specify that T[K] is number type statically?










share|improve this question
















I have a simple Typescript function like this:



function getProperty<T, K extends keyof T>(obj: T, key: K): number 
return obj[key]; // This line is not compiling.
// Typescript will yell: "Type 'T[K]' is not assignable to type 'number'."



My usage looks like this:



const someObj = 
myValue: 123,
otherProperty: '321'


getProperty(someObj, 'myValue')


I won't know what structure of someObj will be.



My question is: How can I specify that T[K] is number type statically?







typescript generics keyof






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 9:50







Joseph Wang

















asked Mar 8 at 9:36









Joseph WangJoseph Wang

658




658







  • 1





    @T.J.Crowder I've updated my use case, thank you!

    – Joseph Wang
    Mar 8 at 9:51












  • 1





    @T.J.Crowder I've updated my use case, thank you!

    – Joseph Wang
    Mar 8 at 9:51







1




1





@T.J.Crowder I've updated my use case, thank you!

– Joseph Wang
Mar 8 at 9:51





@T.J.Crowder I've updated my use case, thank you!

– Joseph Wang
Mar 8 at 9:51












1 Answer
1






active

oldest

votes


















1















I won't know what structure of someObj will be.




Then TypeScript can't really help you with this. TypeScript's type checking is done at compile-time. If the structure of someObj will only be known at runtime, TypeScript can't make access to that structure typesafe. You'd need to know what the property keys and possible values for those properties are at compile-time.



For instance: In your example, the property names are strings and the property values are either strings or numbers (but not booleans or objects, etc.). You can declare a type indexed by strings (since all property names are ultimately strings or Symbols, in this case strings) where the property values are numbers or strings:



declare type SomeObjType = 
[key: string]: number ;


and then getPropertyis:



function getProperty<T extends SomeObjType>(obj: T, key: string): number | string 
return obj[key];



and you can use it like this (in this case, I use JSON.parse to simulate receiving this data from outside the scope of the program):



const someObj: SomeObjType = JSON.parse(`
"myValue": 123,
"otherProperty": "321"
`);

console.log(getProperty(someObj, 'myValue'));
console.log(getProperty(someObj, 'otherProperty'));


On the playground



But that doesn't buy you much, and closes off the possibility that the property values are something other than numbers or strings.



You may need to just use object:



function getProperty(obj: object, key: string) 
return obj[key];


const someObj = JSON.parse(`
"myValue": 123,
"otherProperty": "321"
`);

console.log(getProperty(someObj, 'myValue'));
console.log(getProperty(someObj, 'otherProperty'));


On the playground






share|improve this answer




















  • 1





    Wow, thank you for your detail explanation, T extends SomeObjType works for my use case! Thank you!

    – Joseph Wang
    Mar 8 at 10:08











  • @JosephWang - I'm glad! I suggest that you don't accept the answer right away in this case. (Normally one accepts fairly quickly on SO.) I say that because there are a couple of people who frequently look at unanswered TypeScript questions who know more about TypeScript than I do, so having the question remain unanswered for a few hours will make it more likely they see your question in case there are other approaches that would also help. Don't know what time it is where you are, but perhaps wait a few hours. Happy coding!

    – T.J. Crowder
    Mar 8 at 10:11












  • OK, thank you very much!

    – Joseph Wang
    Mar 8 at 10:14










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%2f55060390%2fhow-can-i-specify-that-typescript-generic-tk-is-number-type%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









1















I won't know what structure of someObj will be.




Then TypeScript can't really help you with this. TypeScript's type checking is done at compile-time. If the structure of someObj will only be known at runtime, TypeScript can't make access to that structure typesafe. You'd need to know what the property keys and possible values for those properties are at compile-time.



For instance: In your example, the property names are strings and the property values are either strings or numbers (but not booleans or objects, etc.). You can declare a type indexed by strings (since all property names are ultimately strings or Symbols, in this case strings) where the property values are numbers or strings:



declare type SomeObjType = 
[key: string]: number ;


and then getPropertyis:



function getProperty<T extends SomeObjType>(obj: T, key: string): number | string 
return obj[key];



and you can use it like this (in this case, I use JSON.parse to simulate receiving this data from outside the scope of the program):



const someObj: SomeObjType = JSON.parse(`
"myValue": 123,
"otherProperty": "321"
`);

console.log(getProperty(someObj, 'myValue'));
console.log(getProperty(someObj, 'otherProperty'));


On the playground



But that doesn't buy you much, and closes off the possibility that the property values are something other than numbers or strings.



You may need to just use object:



function getProperty(obj: object, key: string) 
return obj[key];


const someObj = JSON.parse(`
"myValue": 123,
"otherProperty": "321"
`);

console.log(getProperty(someObj, 'myValue'));
console.log(getProperty(someObj, 'otherProperty'));


On the playground






share|improve this answer




















  • 1





    Wow, thank you for your detail explanation, T extends SomeObjType works for my use case! Thank you!

    – Joseph Wang
    Mar 8 at 10:08











  • @JosephWang - I'm glad! I suggest that you don't accept the answer right away in this case. (Normally one accepts fairly quickly on SO.) I say that because there are a couple of people who frequently look at unanswered TypeScript questions who know more about TypeScript than I do, so having the question remain unanswered for a few hours will make it more likely they see your question in case there are other approaches that would also help. Don't know what time it is where you are, but perhaps wait a few hours. Happy coding!

    – T.J. Crowder
    Mar 8 at 10:11












  • OK, thank you very much!

    – Joseph Wang
    Mar 8 at 10:14















1















I won't know what structure of someObj will be.




Then TypeScript can't really help you with this. TypeScript's type checking is done at compile-time. If the structure of someObj will only be known at runtime, TypeScript can't make access to that structure typesafe. You'd need to know what the property keys and possible values for those properties are at compile-time.



For instance: In your example, the property names are strings and the property values are either strings or numbers (but not booleans or objects, etc.). You can declare a type indexed by strings (since all property names are ultimately strings or Symbols, in this case strings) where the property values are numbers or strings:



declare type SomeObjType = 
[key: string]: number ;


and then getPropertyis:



function getProperty<T extends SomeObjType>(obj: T, key: string): number | string 
return obj[key];



and you can use it like this (in this case, I use JSON.parse to simulate receiving this data from outside the scope of the program):



const someObj: SomeObjType = JSON.parse(`
"myValue": 123,
"otherProperty": "321"
`);

console.log(getProperty(someObj, 'myValue'));
console.log(getProperty(someObj, 'otherProperty'));


On the playground



But that doesn't buy you much, and closes off the possibility that the property values are something other than numbers or strings.



You may need to just use object:



function getProperty(obj: object, key: string) 
return obj[key];


const someObj = JSON.parse(`
"myValue": 123,
"otherProperty": "321"
`);

console.log(getProperty(someObj, 'myValue'));
console.log(getProperty(someObj, 'otherProperty'));


On the playground






share|improve this answer




















  • 1





    Wow, thank you for your detail explanation, T extends SomeObjType works for my use case! Thank you!

    – Joseph Wang
    Mar 8 at 10:08











  • @JosephWang - I'm glad! I suggest that you don't accept the answer right away in this case. (Normally one accepts fairly quickly on SO.) I say that because there are a couple of people who frequently look at unanswered TypeScript questions who know more about TypeScript than I do, so having the question remain unanswered for a few hours will make it more likely they see your question in case there are other approaches that would also help. Don't know what time it is where you are, but perhaps wait a few hours. Happy coding!

    – T.J. Crowder
    Mar 8 at 10:11












  • OK, thank you very much!

    – Joseph Wang
    Mar 8 at 10:14













1












1








1








I won't know what structure of someObj will be.




Then TypeScript can't really help you with this. TypeScript's type checking is done at compile-time. If the structure of someObj will only be known at runtime, TypeScript can't make access to that structure typesafe. You'd need to know what the property keys and possible values for those properties are at compile-time.



For instance: In your example, the property names are strings and the property values are either strings or numbers (but not booleans or objects, etc.). You can declare a type indexed by strings (since all property names are ultimately strings or Symbols, in this case strings) where the property values are numbers or strings:



declare type SomeObjType = 
[key: string]: number ;


and then getPropertyis:



function getProperty<T extends SomeObjType>(obj: T, key: string): number | string 
return obj[key];



and you can use it like this (in this case, I use JSON.parse to simulate receiving this data from outside the scope of the program):



const someObj: SomeObjType = JSON.parse(`
"myValue": 123,
"otherProperty": "321"
`);

console.log(getProperty(someObj, 'myValue'));
console.log(getProperty(someObj, 'otherProperty'));


On the playground



But that doesn't buy you much, and closes off the possibility that the property values are something other than numbers or strings.



You may need to just use object:



function getProperty(obj: object, key: string) 
return obj[key];


const someObj = JSON.parse(`
"myValue": 123,
"otherProperty": "321"
`);

console.log(getProperty(someObj, 'myValue'));
console.log(getProperty(someObj, 'otherProperty'));


On the playground






share|improve this answer
















I won't know what structure of someObj will be.




Then TypeScript can't really help you with this. TypeScript's type checking is done at compile-time. If the structure of someObj will only be known at runtime, TypeScript can't make access to that structure typesafe. You'd need to know what the property keys and possible values for those properties are at compile-time.



For instance: In your example, the property names are strings and the property values are either strings or numbers (but not booleans or objects, etc.). You can declare a type indexed by strings (since all property names are ultimately strings or Symbols, in this case strings) where the property values are numbers or strings:



declare type SomeObjType = 
[key: string]: number ;


and then getPropertyis:



function getProperty<T extends SomeObjType>(obj: T, key: string): number | string 
return obj[key];



and you can use it like this (in this case, I use JSON.parse to simulate receiving this data from outside the scope of the program):



const someObj: SomeObjType = JSON.parse(`
"myValue": 123,
"otherProperty": "321"
`);

console.log(getProperty(someObj, 'myValue'));
console.log(getProperty(someObj, 'otherProperty'));


On the playground



But that doesn't buy you much, and closes off the possibility that the property values are something other than numbers or strings.



You may need to just use object:



function getProperty(obj: object, key: string) 
return obj[key];


const someObj = JSON.parse(`
"myValue": 123,
"otherProperty": "321"
`);

console.log(getProperty(someObj, 'myValue'));
console.log(getProperty(someObj, 'otherProperty'));


On the playground







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 8 at 10:02

























answered Mar 8 at 9:53









T.J. CrowderT.J. Crowder

696k12312401334




696k12312401334







  • 1





    Wow, thank you for your detail explanation, T extends SomeObjType works for my use case! Thank you!

    – Joseph Wang
    Mar 8 at 10:08











  • @JosephWang - I'm glad! I suggest that you don't accept the answer right away in this case. (Normally one accepts fairly quickly on SO.) I say that because there are a couple of people who frequently look at unanswered TypeScript questions who know more about TypeScript than I do, so having the question remain unanswered for a few hours will make it more likely they see your question in case there are other approaches that would also help. Don't know what time it is where you are, but perhaps wait a few hours. Happy coding!

    – T.J. Crowder
    Mar 8 at 10:11












  • OK, thank you very much!

    – Joseph Wang
    Mar 8 at 10:14












  • 1





    Wow, thank you for your detail explanation, T extends SomeObjType works for my use case! Thank you!

    – Joseph Wang
    Mar 8 at 10:08











  • @JosephWang - I'm glad! I suggest that you don't accept the answer right away in this case. (Normally one accepts fairly quickly on SO.) I say that because there are a couple of people who frequently look at unanswered TypeScript questions who know more about TypeScript than I do, so having the question remain unanswered for a few hours will make it more likely they see your question in case there are other approaches that would also help. Don't know what time it is where you are, but perhaps wait a few hours. Happy coding!

    – T.J. Crowder
    Mar 8 at 10:11












  • OK, thank you very much!

    – Joseph Wang
    Mar 8 at 10:14







1




1





Wow, thank you for your detail explanation, T extends SomeObjType works for my use case! Thank you!

– Joseph Wang
Mar 8 at 10:08





Wow, thank you for your detail explanation, T extends SomeObjType works for my use case! Thank you!

– Joseph Wang
Mar 8 at 10:08













@JosephWang - I'm glad! I suggest that you don't accept the answer right away in this case. (Normally one accepts fairly quickly on SO.) I say that because there are a couple of people who frequently look at unanswered TypeScript questions who know more about TypeScript than I do, so having the question remain unanswered for a few hours will make it more likely they see your question in case there are other approaches that would also help. Don't know what time it is where you are, but perhaps wait a few hours. Happy coding!

– T.J. Crowder
Mar 8 at 10:11






@JosephWang - I'm glad! I suggest that you don't accept the answer right away in this case. (Normally one accepts fairly quickly on SO.) I say that because there are a couple of people who frequently look at unanswered TypeScript questions who know more about TypeScript than I do, so having the question remain unanswered for a few hours will make it more likely they see your question in case there are other approaches that would also help. Don't know what time it is where you are, but perhaps wait a few hours. Happy coding!

– T.J. Crowder
Mar 8 at 10:11














OK, thank you very much!

– Joseph Wang
Mar 8 at 10:14





OK, thank you very much!

– Joseph Wang
Mar 8 at 10:14



















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%2f55060390%2fhow-can-i-specify-that-typescript-generic-tk-is-number-type%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

Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived