Default value for typescript type alias

Viewed 24390

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?

3 Answers

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: () => {}
}

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

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

Related