Yes, easily, and you don't need to add a class constructor.

export class Profile extends ServerData {
  name: string;
  email: string;
  age: number = 0;
}

The ability to define default values is one of the main things that differentiates a class from an interface.

For this to work you need to call new Profile() somewhere in your code, otherwise a class instance won't be created and you won't have defaults set, because the above TypeScript will compile to the following JavaScript:

var Profile = /** @class */ (function () {
    function Profile() {
        this.age = 0;
    }
    return Profile;
}());

So just using it for type assertion at compile-time isn't sufficient to set a default at run-time.

See it in action in the TypeScript Playground.

Answer from msanford on Stack Overflow
Top answer
1 of 5
53

Yes, easily, and you don't need to add a class constructor.

export class Profile extends ServerData {
  name: string;
  email: string;
  age: number = 0;
}

The ability to define default values is one of the main things that differentiates a class from an interface.

For this to work you need to call new Profile() somewhere in your code, otherwise a class instance won't be created and you won't have defaults set, because the above TypeScript will compile to the following JavaScript:

var Profile = /** @class */ (function () {
    function Profile() {
        this.age = 0;
    }
    return Profile;
}());

So just using it for type assertion at compile-time isn't sufficient to set a default at run-time.

See it in action in the TypeScript Playground.

2 of 5
25

The reason you're seeing overwriting properties is due to type erasure in TypeScript. TypeScript has no idea what types of objects are assigned to its variables during runtime. This would seem somewhat strange to you if you're coming not from a java / c# background.

Because in the end , it's just JavaScript. And JavaScript doesn't enforce strict type checking.

In order to ensure that your profile objects always have an age property, you could create your own objects then copy over the values you get from the response. This is the usual approach when it comes to wire format to domain object mapping.

To do this first create your domain model, a Profile class with a default age property in this case.

 export class Profile {
        constructor(
            public name: string,
            public email: string,
            public age: number = 0) { }
    }

Then map your response to the domain model.

this.resultsManagerService.getResults(this.config.request.action, this.pagingAndSorting, this.args).subscribe(
  results => {
    let res = (results as Profile[]).map((profile) => new Profile(profile.name, profile.email, profile.age));
    this.results = this.results.concat(res);
 });
🌐
Reddit
reddit.com › r/typescript › how do i pass a default value if object is undefined
r/typescript on Reddit: how do I pass a default value if object is undefined
March 30, 2022 -

I have a class like this but I want to initialize a default value for Id and email when there is no data. How do I do that? As you see, I want to set the default value if I pass new Recipient ()

const user = this.options.find(x=>x.id == 1);

return user? new Recipient (id:user.id, email:user.email): new Recipient ();

export class Recipient {
    id: number;
    email?: string;
    constructor(data?: Partial<Recipient>) {
        Object.assign(this, data);
    }
}

=======================Update======================

eventually I chose one of two options

export class Recipient {
    id: number;
    email?: string;
    constructor(data?: Partial<Recipient>) {
        this.id = data?.id || 0;
        this.email = data?.email || null;
    }
}
export class Recipient {
    id: number;
    email?: string;
    constructor(data?: Partial<Recipient>) {
        Object.assign(this,{id:0, email :null}, data);
    }
}

Top answer
1 of 2
11
I don't really understand why you loosely Type something when the whol point of TS is to use strict typing. But assuming you have a genuine use case here you can assign defulat values when declaring properties inside the class. Like so export class Recipient { id: number = 1; email?: string = somedfault@email.com; } Here 1 will be assigned a default value to number and same goes for the email ass well. And if you pass in a value in the constructor during the instantiatio of the class that will override the id and the email. Do remeber to check and assign values in the constructor toneaxh of these properties else they will always default to the above values.👍
2 of 2
2
The Recipient type export class Recipient { id: number; email?: string; constructor(data?: Partial) { this.id = data?.id || 0; this.email = data?.email || null; } } allows to create the following combinations: id | email | 0 | undefined | 0 | null | number | undefined | number | null | number | string If any of those combinations are invalid in your domain, then it's a possible bug waiting to happen. Not to count, you need to handle both null and undefined. With strict enabled, two combinations are gone because this.email = data?.email || null; wouldn't compile . Then, you'd be left with something like: id | email | 0 | undefined | number | undefined | number | string Do they all make sense in your domain? Could you misuse any of them? I could imagine that a Recipient with id 0 represents one to save in the database: const saveRecipient = (recipient: Recipient) => // ... The issue is that you can now call saveRecipient with an id 0 and, if you forget to check what's the value of the id, the database would either raise an error or do something silly (eg, actually use id 0). Personally, I like to be really strict with types so that I don't have to remember to perform checks—the compiler reminds me: type PersistedRecipient = { id: number, email: string } type NewRecipient = { email: string } // or Omit const saveRecipient = (recipient: Recipient) => // ... Notice, I cannot call saveRecipient with a value of type PersistedRecipient.
Discussions

How to set default class property value in TypeScript declaration file?
How do I declare that foo has a default value (or initial value) of, say, 60. ... 4 foo: number = 60 ~~ path/to/something.js/Foo.d.ts/(4,28): error TS1039: Initializers are not allowed in ambient contexts. ... Good point! I suppose the runtime code does that anyway. ... Haha, that should be the answer! ... Try removing declare from your class ... More on stackoverflow.com
🌐 stackoverflow.com
Add support for prototype-based property default values
However, it also has some surprising effects when the value is the result of a more complex expression, or in case we want the variable to refer to a shared instance. As a consequence, writing code that share an instance requires either to use a separate variable or manually patch the prototype after creating the class: ... My proposal would be to add a new property modifier that would define a default ... More on github.com
🌐 github.com
9
May 5, 2017
Init class instance in one line and respect default values with DRY principle
This is already possible, but it's a bit hard to respect default values of the class, without re-assign them. In my case I have a simply model class which width attribute. This class is indent for configuration purpose, so it's mainly used in my configuration object (which is based on TypeScript, ... More on github.com
🌐 github.com
3
October 18, 2018
angular - TypeScript Default Value for property - Stack Overflow
Thanks, with a click event to run above code, it will the run the constructor, and the default value will be set. But for a model binding in Angular, it will not work. I have updated my post with updated code. 2017-06-07T09:52:24.273Z+00:00 ... class User { constructor(public id: number = -1, ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-class-with-default-values
Set default values for Class properties in TypeScript | bobbyhadz
We created an Employee class with default values for various properties. Notice that when we assigned default values for string and number literals, we didn't have to explicitly specify the type. TypeScript is able to infer the type of the id, name and country properties based on the default values we provided.
🌐
TypeScript
typescriptlang.org › docs › handbook › 2 › classes.html
TypeScript: Documentation - Classes
The static members of a generic class can never refer to the class’s type parameters. ... It’s important to remember that TypeScript doesn’t change the runtime behavior of JavaScript, and that JavaScript is somewhat famous for having some peculiar runtime behaviors. JavaScript’s handling of this is indeed unusual: ... Long story short, by default, the value of this inside a function depends on how the function was called.
🌐
GitHub
github.com › microsoft › TypeScript › issues › 15607
Add support for prototype-based property default values · Issue #15607 · microsoft/TypeScript
May 5, 2017 - Currently when defining a class, the default values assigned to property are set by the constructor of the class: class A { map: { [key: string]: string } = {}; } Generates the following code: class A { constructor() { this.map = {}; } }...
Author   Fruneau
🌐
Squash
squash.io › how-to-set-default-values-in-typescript
How to Set Default Values in TypeScript - Squash Labs
October 14, 2023 - Default initialization is a feature in TypeScript that allows you to assign default values to class properties. When a class instance is created, these properties will be initialized with their default values if no other value is provided.
🌐
GitHub
github.com › microsoft › TypeScript › issues › 27968
Init class instance in one line and respect default values with DRY principle · Issue #27968 · microsoft/TypeScript
October 18, 2018 - export class MyClass { Field1: string = "" Field2: string = "DefaultValue" } it's not possible to initialize it with a custom Field1 value and leave Field2 to it's default value like this:
Author   weber-d
Find elsewhere
🌐
bet365 Careers
bet365techblog.com › default-values-typescript
Efficient Default Property Values in TypeScript
September 15, 2017 - The goal is to be the world's number one sports betting and gaming company. To achieve this, our combined values ensure we work together and deliver on that goal.
🌐
Areknawo
areknawo.com › typescript-introduction-pt2
TypeScript introduction - part II
April 3, 2019 - If you won’t declare a property earlier, you’ll get an access error. Declaration of class member is nothing more than specifying its name and type, inside the given class as in the example above. Optionally, you can also assign a default value for your member, right at the moment of its ...
🌐
TypeScript Tutorial
typescripttutorial.net › home › typescript tutorial › typescript default parameters
TypeScript Default Parameters
June 2, 2020 - Use default parameter syntax parameter:=defaultValue if you want to set the default initialized value for the parameter.
🌐
Medium
medium.com › @kidaneberihuntse › simplifying-typescript-functions-with-default-parameter-values-d07bc6c54fa3
Simplifying TypeScript Functions with Default Parameter Values | by Kidu BT | Medium
March 29, 2024 - Let’s dive into how these features work together to streamline function declarations. To set a default value for a function parameter in TypeScript, you simply assign the default value directly in the parameter declaration.
🌐
GitHub
github.com › mrdoob › three.js › issues › 19919
Add default values to TypeScript declaration files · Issue #19919 · mrdoob/three.js
July 24, 2020 - Having definitions helps a lot but they are lacking the proper setting of the default value. It is usually in the comment just above each property so is there any blocker to include them as well. ... * If autoClear is true, defines whether the renderer should clear the color buffer. Default is true. ... * If autoClear is true, defines whether the renderer should clear the depth buffer. Default is true. ... * If autoClear is true, defines whether the renderer should clear the stencil buffer. Default is true. ... export class WebGLRenderer implements Renderer { // ...
Author   dmnsgn
🌐
Reddit
reddit.com › r/typescript › i am struggling with default types.
r/typescript on Reddit: I am struggling with default types.
January 21, 2024 -

So I usually create an object for a functionality in my app. But how should I give default values to variables until they are declared? It's a little complicated so TS can't infere it by itself.

I am a beginner so thanks for any help :)

export const DOM = {
    root: document.documentElement,
    html: document.documentElement,
    body: document.body,
    img: /* what am I  supposed to put here */,

/* this is inited from another function */
    async init() {
        this.createImgContainer();
    },
    createImg() { 
        this.img = document.body.firstElementChild as HTMLImageElement;
    };
}

🌐
TSDoc
tsdoc.org › pages › tags › defaultvalue
@defaultValue | TSDoc
This block tag is used to document the default value for a field or property, if a value is not assigned explicitly. This tag should only be used with fields or properties that are members of a TypeScript class or interface.
🌐
GitHub
github.com › microsoft › TypeScript › issues › 15648
Default class parameter values stomp value set in constructor when subclassing · Issue #15648 · microsoft/TypeScript
May 8, 2017 - TypeScript currently sets default class param values at the end of the constructor if that constructor doesn't already set a value. In fact, it's smart enough that if the constructor calls another function that sets the value, the default won't ...
Author   btraut