interface Human {
firstName: string;
lastName: string;
}
let human1: Human = {};
human1.firstName = "John"
human1.lastName = "Doe"
Upon declaring human1, an error pops up:
Type '{}' is missing the following properties from type Human
interface Human {
firstName: string;
lastName: string;
}
let human1: Human = {};
human1.firstName = "John"
human1.lastName = "Doe"
Upon declaring human1, an error pops up:
Type '{}' is missing the following properties from type Human
Here is an improved approach:
let person1: Person = {name: '', surname: ''};
If you specifically need an empty object, you can do it like this:
let person1: Person = {} as Person;
Update following a comment:
Take a look at the unpredictableFunction
:
const unpredictableFunction = (): string|number|string[] => {
return Math.random() > 0.5 ? 'string' : Math.random() > 0.5 ? 9999 : ['1', '2', '3']
};
This function may return a number, a string, or an array of strings.
const person: Person = {name: '', surname: ''};
person.name = unpredictableFunction (); // this illustrates your point
In such a scenario, you will encounter
Type 'string | number | string[]' is not assignable to type 'string'.
Solutions include:
Review your code and ensure only strings are assigned to Person properties,
Alternatively, modify the interface to accommodate different value types:
interface Person {
name: string | number | string[];
surname: string;
}
If you have created an interface with two mandatory properties, when creating an object with the Person interface type, you need to specify these properties immediately like so:
let person: Person = {
name: '',
surname: ''
}
However, if you consider these properties to be optional rather than mandatory, you can modify your interface as follows:
interface Person {
name?: string;
surname?: string;
}
By using the ?
symbol, you indicate that the property is optional. The following code should now function correctly:
let person: Person = {};
Enhanced functionality in Typescript 2.0
let person1 ! : Person;
The exclamation mark "!" signifies the Non-null assertion operator
Referencing the official documentation
A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.
Simply include the following code in your TypeScript file:
} | {};
In my application, I am creating a unique feature where users can trigger a window to appear by inputting the symbol @ (shift + 50). This will allow them to access predefined variables... <textarea @keyup.shift.50="showWindow"></textarea> My ...
Here is an illustration of code with two files and "classes". In the CRUD class, there is a problem with this.modelName when setting routes as it changes the context. The question arises on how to maintain the same scope within the CRUD where modelName is ...
Creating a CRUD view in Cake PHP is simple with the following command: bin/cake bake all users This command builds the users table for CRUD operations. Is there a JavaScript framework that offers similar simplicity? ...
After scouring through numerous modules, I couldn't find one that worked with TypeScript, including mongoose-slug-generator and mongoose-slug-plugin. ...
I'm struggling with handling types in my TypeScript application, especially with the TaskListProps interface. export default interface TaskListProps { tasks: [ { list_id: string; title: string; description: string; status ...
I need help with a TypeScript-related issue. I am struggling to implement the expected return type for the function dataSources in this scenario. Here is the code snippet: const dataSources = () => { quizzessApi: new QuizzessDataSource(); } const ...
I am facing an issue while trying to connect my local mongoDB docker, named "some-mongo", to my NodeJS backend server running on the same computer. The problem arises when attempting to establish the connection using the "mongoose" module. To launch my mo ...
Encountering this error is becoming a frequent occurrence for me, and I am currently unable to resolve it. src/graphics.ts:105:55 - error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. 105 _queue.forEach((_ ...
Array; arr=[ { id: [ '5e6e9b0668fcbc7bce2097ac', '5e6e9b0e68fcbc7bce2097af' ], color: [ 'a', 'b' ] } ] Models; const varyant = Models.varyant function; Promise.all( arr.map((item)=>{ return var ...
Here's the code in question: let newArr = [] const items = [ { name: 'JTB 0110-01', offers: ['one', 'two'] }, { name: 'LOBA CHEMIE', offers: ['three', &apos ...
I have implemented Select2 for custom dropdown styling. The options are structured like this: <option value="001,100">Option 001</option> <option value="002,200">Option 002</option> <option value="003,300">Option 003</opti ...
For my upcoming college project, I am tasked with developing a movie library. The main page of the library will feature various movie posters. Upon clicking on a poster, users will be directed to a dedicated page displaying detailed information about the ...
I am currently experiencing an issue with my code for searching. When I search the full text, it works fine but when I search for a middle character, it does not work as expected. For instance, searching for "apple" or "ap" works correctly, however, if I ...
When working with JavaScript, it is important to consider the best practices for performance optimization. Take a look at these two examples: Example 1: var x = {}; x.a = 10; Example 2: var x = {}; x = {a: 10}; Are there any noticeable differences in ...
Can you guide me on how to use jQuery to implement a click function that sets the status value to 'true' if a checkbox is checked, and 'false' if it's not checked? If Checkbox 1 is checked, Status 1 should be set to true. Similarl ...
I am trying to dynamically add a rule to my CSS for each element. Each rule should have a different background-image and name. However, I seem to be encountering an issue where the dynamically added div is not linking to the dynamically added CSS rule. I&a ...
I have developed a php script to create json data. However, I am facing an issue while trying to display this generated json data in a table. While my php code successfully generates the data, it is unable to insert it into the table. I would appreciate an ...
When using fabric js, I have successfully drawn various shapes like circles and rectangles. However, I encountered an issue while trying to obtain the coordinates of the rectangle using the fabric.rect() method. canvas.getActiveObject().get('points& ...
I came across this code on jsfiddle, and I really want to incorporate it into my PHP file. However, when I tried to do so, it didn't work even though I simply copied and pasted the code without making any changes. Here is my code: <!DOCTYPE html& ...
I am facing an interesting challenge in my Node.js project where I need to connect multiple MongoDB databases. Let me share with you my current setup and the issue that is causing me some trouble. Node Version: v6.12.1 Express.js Version: 4.16.2 Mongoos ...