- Typescript how to get specific property from object
- How to access object properties from TypeScript?
- Get property names of object
- How to get data from an TypeScript Object?
- Is there a way to get all required properties of a typescript object
- How to Get an Object Value By Key in TypeScript
- Dot notation property access
- Bracket notation property access
- Computed property names
- Every Crazy Thing JavaScript Does
Typescript how to get specific property from object
Like this: And an example usage: That doesn’t play nicely with types with index signatures: Not sure if your use case cares about indexable types or not. The solution relies on conditional types and the fact that the empty object type is considered assignable to a weak type (a type with no required properties).
How to access object properties from TypeScript?
The Enterprise model/schema that you created in Mongoose in Node.js resides on the server side. If you want the TypeScript code on the UI to recognize the properties in Enterprise , you will have to create a class in your angular codebase.
Create a folder named, say, models at the same level as your services folder. (Optional)
Create two files named site.ts and enterprise.ts in the models folder created in the previous step (You can put these file at a different location if you want) with the following contents:
enterprise.ts
import < Site >from './site'; export interface Enterprise
Now, inside the EntrepriseComponent file, add the following imports
import < Enterprise>from '../models/entreprise'; import < Site >from '../models/site';
And change the first lines inside the EntrepriseComponent file to
export class EntrepriseComponent implements OnInit < entreprise: Enterprise = <>; sites: Site[] = [];
Now, the enterprise attribute will be of type Enterprise and you will be able to access the properties that we declared in the enterprise.ts file.
Update: Also, you cannot console.log(this.enterprise.name) immediately after this.getEntrepriseById(this.id); in your ngOnInit() function. This is because the web service you are making to get the enterprise object would not have resolved when you are trying to log it to the console.
If you want to see the enterprise object in the console or you want to run some code that needs to run after the service call has resolved and the this.enterprise object has a value, the best place to do this would be your getEntrepriseById function. Change the getEntrepriseById function to
getEntrepriseById(id) < this.entrepriseService.getEntreprise(id).subscribe( data =>< this.enterprise = data; console.log(this.enterprise.name); // Any code to run after this.enterprise resolves can go here. >, error => console.log(error) ); >
How to get object values as type in typescript?, 1 Answer. Sorted by: 3. Might be a more concise method, but you can use keyof typeof MY_CONST to get the keys of the object, and look up those keys on the MY_CONST type: type MY_TYPE = typeof MY_CONST Get object property typescript; Also note that when you have lots of properties, as const on the …
Get property names of object
You need to remember that TypeScript is mostly syntactic sugar on top of JavaScript. Everything that does not have an immediate effect on JavaScript will not carry over when compiling your TypeScript code.
In this case, you have member declarations. The primary feature of this is to define which members an object may have. JavaScript itself does allow you to set arbitrary members on any object, so having member declarations on a TypeScript type restricts which members you have access to.
For your particular case, you declare two valid members on your class: myProperty and otherProperty . In addition, you also initialize otherProperty with a value.
Think about what happens in JavaScript land at this point: Member declarations do not exist, so all that’s left is the initialized member otherProperty . In particular, this is what your class declaration compiles to in JavaScript:
As you can see, there is no myProperty because nothing is ever assigned to it. So for the JavaScript side, it does not exist (yet).
This means that at run-time (JavaScript is the run-time of TypeScript), the only property that exists an object of type Simple is otherProperty which is why that’s the only one you get when inspecting your object.
Javascript extract certain properties from all objects in, Here a function that take an object, and extract only the properties that you want. Which you passe through an array as a second parameter. Advantage: more straight forward and cleaner. Specially when you need to extract from just one object. If you have a list of object. Map through the list and extract in every …
How to get data from an TypeScript Object?
For this particular problem, it is better to use interface :
Now you can access it easily .
Typescript — Get property names of object, I want to get the property names of a simple Typescript object. export class Simple < myProperty: string; otherProperty: string = "some text"; >var s = new Simple(); Object For your particular case, you declare two valid members on your class: myProperty and otherProperty.
Is there a way to get all required properties of a typescript object
At runtime this is not possible, because requiredness/optionality of a property only exists in the TypeScript type system, which has been erased by the time the code actually runs. You can add your own runtime information via decorators or the like, but for that you need to modify the actual code that generates the classes and objects. So getting an array of required property names given an object or constructor is not possible.
At design time it is possible to extract the required/optional keys of a type, as a subtype of keyof T . The solution relies on conditional types and the fact that the empty object type <> is considered assignable to a weak type (a type with no required properties). Like this:
type RequiredKeys = < [K in keyof T]-?: <>extends Pick ? never : K >Get object property typescript; type OptionalKeys = < [K in keyof T]-?: <>extends Pick ? K : never >Get object property typescript;
interface SomeType < required: string; optional?: number; requiredButPossiblyUndefined: boolean | undefined; >type SomeTypeRequiredKeys = RequiredKeys; // type SomeTypeRequiredKeys = "required" | "requiredButPossiblyUndefined" 🙂 type SomeTypeOptionalKeys = OptionalKeys; // type SomeTypeOptionalKeys = "optional" 🙂
That doesn’t play nicely with types with index signatures:
interface SomeType < required: string; optional?: number; requiredButPossiblyUndefined: boolean | undefined; [k: string]: unknown; // index signature >type SomeTypeRequiredKeys = RequiredKeys; // type SomeTypeRequiredKeys = never 🙁 type SomeTypeOptionalKeys = OptionalKeys; // type SomeTypeOptionalKeys = string 🙁
Not sure if your use case cares about indexable types or not. If so, there is a more complex solution which handles that by first extracting known literal keys and then checking for required/optional:
(EDIT: the following was updated to work around a breaking change in TS4.3, see ms/TS#44143)
type RequiredLiteralKeys = keyof < [K in keyof T as string extends K ? never : number extends K ? never : <>extends Pick ? never : K]: 0 > type OptionalLiteralKeys = keyof < [K in keyof T as string extends K ? never : number extends K ? never : <>extends Pick ? K : never]: 0 > type IndexKeys = string extends keyof T ? string : number extends keyof T ? number : never;
type SomeTypeRequiredKeys = RequiredLiteralKeys; // type SomeTypeRequiredKeys = "required" | "requiredButPossiblyUndefined" 🙂 type SomeTypeOptionalKeys = OptionalLiteralKeys; // type SomeTypeOptionalKeys = "optional" 🙂 type SomeTypeIndexKeys = IndexKeys; // type SomeTypeIndexKeys = string 🙂
type _OptionalKeys = < [K in KnownKeys& KnownKeys]: Pick extends Pick ? never : K >; /** * OptionalKeys grabs the keys which are optional from a type `T`. * For example, `< a: string; b: string | undefined; c?: string >` => `'c'`. */ export type OptionalKeys = _OptionalKeys < T, Required>[KnownKeys];
Basically, we’re checking for OptionalKeys so that we can then extract the RequiredKeys.
/** * RequiredKeys grabs the keys which are required from a type `T`. * For example, `< a: string; b: string | undefined; c?: string >` => `'b' | 'c'`. */ export type RequiredKeys = Exclude< KnownKeys, OptionalKeys >;
/** * Extracts the keys of a union type */ // tslint:disable-next-line:no-any export type KeysOfUnion = T extends any ? keyof T : never; /** * Extracts the known keys from an object – regardless of whether it has an * index signature. */ export type KnownKeys = < [K in keyof T]: string extends K ? never : number extends K ? never : K >extends < [_ in keyof T]: infer U >? <> extends U ? never : U : never;
Of course, you could invert this approach, so you’d find RequiredKeys first, and then find OptionalKeys by changing around the Pick extends Pick to Pick extends Pick in _OptionalKeys making it _RequiredKeys .
So this solution (I created it for my rbx package) works on union types as well as singleton types.
Typescript — Safe way to extract property names, Right now there’s not really a great way of doing this, but there are currently some open suggestions on github (See #1579, #394, and #1003).. What you can do, is what’s shown in this answer—wrap referencing the property in a function, convert the function to a string, then extract the property name out of …
How to Get an Object Value By Key in TypeScript
You can easily get an object’s value by a key in Typescript using bracket notation, i.e., obj[‘key’] , obj[myVar] , etc. If the key exists, you will get the corresponding value back.
type Car = < name: string; maxSpeed: number; color: string; >; const car: Car = < name: 'CB Flash', maxSpeed: 200, color: 'blue', >; console.log(car[‘name’]); // CB Flash // Dot notation console.log(car.name); // CB Flash // Get value by variable key const prop = ‘name’; console.log(car[prop]); // CB Flash // Computed property key const val = car[3 > 1 ? ‘name’ : ‘maxSpeed’] console.log(val) // CB Flash
Dot notation property access
There are two ways to get an object’s value by a property key in TypeScript: dot notation and bracket notation.
In dot notation, we access an object value with the obj.propKey syntax.
type Car = < name: string; maxSpeed: number; color: string; >; const car = < name: 'CB Flash', maxSpeed: 200, color: 'blue', >; console.log(car.name); // CB Flash console.log(car.maxSpeed); // 200 console.log(car.color); // blue
With the obj.propKey syntax, the propKey must be a valid TypeScript identifier. Otherwise, a syntax error will be thrown:
type Car = < [propKey: string]: string >; const car: Car = <>; car.100 = ‘go faster’; // ❌ SyntaxError console.log(car.100); // ❌ SyntaxError
propKey can also be a reserved keyword, like let , var , async , etc.
type Car = < [propKey: string]: string >; const car: Car = <>; car.let = ‘works’; car.await = ‘works too’; console.log(car.let); // works console.log(car.await); // works too
Bracket notation property access
In bracket notation, we access the property value with the obj[expression] syntax. The expression should evaluate to a string or Symbol that represent the property’s key.
Unlike dot notation, with bracket notation, we can access keys that are not valid TypeScript identifiers, like numbers and keys containing spaces.
type Car = < [propKey: string]: string >; const car: Car = <>; car[‘100’] = ‘go faster’; car[‘year produced’] = 2022; console.log(car[‘100’]); // go faster console.log(car[‘year produced’]); // 2022
Computed property names
The expression we put in-between the brackets can be as complex as possible, as long it evaluates to a string or Symbol.
For example, we can put a ternary expression in-between the brackets:
type Car = < name: string; maxSpeed: number; color: string; >; const car: Car = < name: 'CB Flash', maxSpeed: 200, color: 'blue', >; const num = 3; const val = car[num > 1 ? ‘name’ : ‘maxSpeed’]; console.log(val); // CB Flash
Note: If the expression to the left of the ? is truthy, the ternary operator returns the value to the left. Otherwise, it returns the value to the right.
The ternary expression evaluates to the ‘name’ key, so the corresponding property value is returned.
You can also this computed property names approach to set a new property on a object.
type Car = < [propKey: string]: string | number; >; const car: Car = <>; const num = 7; car[num > 10 ? ‘name’ : ‘maxSpeed’] = 500; console.log(car[‘name’]); // undefined console.log(car[‘maxSpeed’]); // 500
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.