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
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
add a comment |
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
1
@T.J.Crowder I've updated my use case, thank you!
– Joseph Wang
Mar 8 at 9:51
add a comment |
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
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
typescript generics keyof
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
add a comment |
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
add a comment |
1 Answer
1
active
oldest
votes
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 getProperty
is:
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
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
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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 getProperty
is:
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
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
add a comment |
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 getProperty
is:
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
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
add a comment |
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 getProperty
is:
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
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 getProperty
is:
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
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
1
@T.J.Crowder I've updated my use case, thank you!
– Joseph Wang
Mar 8 at 9:51