30

Can typescript type alias support default arguments? For instance:

export type SomeType = {
    typename: string;
    strength: number;
    radius: number;
    some_func: Function;
    some_other_stat: number = 8; // <-- This doesn't work
}

The error is A type literal property cannot have an initializer.

I can't find documentation relating to this - type keyword is very obscure behind everything else that is also named type. Is there anything I can do to have default argument value for type in typescript?

1
  • Haha! a very C# dev question
    – Andy
    Jul 29, 2022 at 11:05

3 Answers 3

33

You cannot add default values directly to a type declaration.

You can do something like this instead:

// Declare the type
export type SomeType = {
    typename: string;
    strength: number;
    radius: number;
    some_func: Function;
    some_other_stat: number;
}

// Create an object with all the necessary defaults
const defaultSomeType = {
    some_other_stat: 8
}

// Inject default values into your variable using spread operator.
const someTypeVariable: SomeType = {
  ...defaultSomeType,
  typename: 'name',
  strength: 5,
  radius: 2,
  some_func: () => {}
}
2
  • 2
    And how do you do this when someTypeVariable is injected into a function?
    – Marcus
    Jul 11, 2021 at 15:15
  • 1
    @Marcus you can extract function parameters (see "Unpacking properties from objects passed as a function parameter") and give them default values directly. If you are confused, please, make a new question and tag me.
    – Cat-Lord
    Jun 27, 2022 at 15:06
12

Type does not exist in runtime, so a default value makes no sense. If you want to have a default default, you must use something that exists in runtime, such as a class or a factory function

0

You can't add default values directly to type.

I would suggest the following instead

type Person = {
    name: string
    age?: number // Add '?' such that Pick allows you to skip the field (i.e. not force to set))
    country?: string
    readonly createTime: string
    Say(msg: string): string
}

function NewPerson(name: string, options?: Pick<Person, "country" | "age">): Person {
    const createTime = new Date().toISOString() // Here you can set the default value
    const defaults = {
        createTime,
        Say(msg: string): string { // Implement the method
            return msg
        }
    }
    return {
        name,
        ...options,
        ...defaults,
    }
}

const carson = NewPerson("Carson", {age:30})
console.log(carson.name)
console.log(carson.createTime)
console.log(carson.Say("hello world"))
const bar = NewPerson("Bar")
console.log(bar)

playground

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.