Typescript interface default values

前端 未结 10 1953
借酒劲吻你
借酒劲吻你 2020-12-02 14:44

I have the following interface in TypeScript:

interface IX {
    a: string,
    b: any,
    c: AnotherType
}

I declare a variable of that t

相关标签:
10条回答
  • 2020-12-02 15:39

    While @Timar's answer works perfectly for null default values (what was asked for), here another easy solution which allows other default values: Define an option interface as well as an according constant containing the defaults; in the constructor use the spread operator to set the options member variable

    interface IXOptions {
        a?: string,
        b?: any,
        c?: number
    }
    
    const XDefaults: IXOptions = {
        a: "default",
        b: null,
        c: 1
    }
    
    export class ClassX {
        private options: IXOptions;
    
        constructor(XOptions: IXOptions) {
            this.options = { ...XDefaults, ...XOptions };
        }
    
        public printOptions(): void {
            console.log(this.options.a);
            console.log(this.options.b);
            console.log(this.options.c);
        }
    }
    

    Now you can use the class like this:

    const x = new ClassX({ a: "set" });
    x.printOptions();
    

    Output:

    set
    null
    1
    
    0 讨论(0)
  • 2020-12-02 15:42

    It is depends on the case and the usage. Generally, in TypeScript there are no default values for interfaces.

    If you don't use the default values
    You can declare x as:

    let x: IX | undefined; // declaration: x = undefined
    

    Then, in your init function you can set real values:

    x = {
        a: 'xyz'
        b: 123
        c: new AnotherType()
    };
    

    In this way, x can be undefined or defined - undefined represents that the object is uninitialized, without set the default values, if they are unnecessary. This is loggically better than define "garbage".

    If you want to partially assign the object:
    You can define the type with optional properties like:

    interface IX {
        a: string,
        b?: any,
        c?: AnotherType
    }
    

    In this case you have to set only a. The other types are marked with ? which mean that they are optional and have undefined as default value.

    In any case you can use undefined as a default value, it is just depends on your use case.

    0 讨论(0)
  • 2020-12-02 15:44

    You can't set default values in an interface, but you can accomplish what you want to do by using Optional Properties (compare paragraph #3):

    https://www.typescriptlang.org/docs/handbook/interfaces.html

    Simply change the interface to:

    interface IX {
        a: string,
        b?: any,
        c?: AnotherType
    }
    

    You can then do:

    let x: IX = {
        a: 'abc'
    }
    

    And use your init function to assign default values to x.b and x.c if those properies are not set.

    0 讨论(0)
  • 2020-12-02 15:47

    My solution:

    I have created wrapper over Object.assign to fix typing issues.

    export function assign<T>(...args: T[] | Partial<T>[]): T {
      return Object.assign.apply(Object, [{}, ...args]);
    }
    

    Usage:

    env.base.ts

    export interface EnvironmentValues {
    export interface EnvironmentValues {
      isBrowser: boolean;
      apiURL: string;
    }
    
    export const enviromentBaseValues: Partial<EnvironmentValues> = {
      isBrowser: typeof window !== 'undefined',
    };
    
    export default enviromentBaseValues;
    

    env.dev.ts

    import { EnvironmentValues, enviromentBaseValues } from './env.base';
    import { assign } from '../utilities';
    
    export const enviromentDevValues: EnvironmentValues = assign<EnvironmentValues>(
      {
        apiURL: '/api',
      },
      enviromentBaseValues
    );
    
    export default enviromentDevValues;
    
    0 讨论(0)
提交回复
热议问题