我在TypeScript中有以下接口:

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

我声明了一个该类型的变量并初始化了所有属性

let x: IX = {
    a: 'abc',
    b: null,
    c: null
}

然后在稍后的init函数中为它们赋值

x.a = 'xyz'
x.b = 123
x.c = new AnotherType()

但我不喜欢在声明对象时为每个属性指定一堆默认空值,因为它们稍后将被设置为实值。我能告诉接口默认属性我不提供为空吗?是什么让我这样做:

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

而不会产生编译器错误。现在它告诉我了

TS2322:类型“{}”不能赋值给类型 “九”。属性“b”在类型“{}”中缺失。


当前回答

在有很多参数的情况下,最好让用户只插入几个参数,而且没有特定的顺序。

例如,不好的做法:

foo(a?, b=1, c=99, d=88, e?)
foo(null, null, null, 3)

因为你必须在你真正想要的参数(d)之前提供所有参数。

好的做法是:

foo({d=3})

实现它的方法是通过接口。 你需要将参数定义为一个接口,像这样:

interface Arguments {
    a?;
    b?; 
    c?;
    d?;
    e?;
}

并像这样定义函数:

foo(arguments: Arguments)

现在接口变量不能得到默认值,那么我们如何定义默认值呢?

简单,我们为整个接口定义默认值:

foo({
        a,
        b=1,
        c=99,
        d=88,
        e                    
    }: Arguments)

现在如果用户通过:

foo({d=3})

实际参数为:

{
    a,
    b=1,
    c=99,
    d=3,
    e                    
}

另一个不声明接口的选项是:

foo({
        a=undefined,
        b=1,
        c=99,
        d=88,
        e=undefined                    
    })

跟进: 在前面的函数定义中,我们为参数对象的字段定义了默认值,但没有为对象本身定义默认值。 因此,我们将从下面的调用中得到一个提取错误(例如不能读取未定义的属性'b'):

foo()

有两种可能的解决方案:

1.

const defaultObject = {a=undefined, b=1, c=99, d=88, e=undefined}
function foo({a=defaultObject.a, b=defaultObject.b, c=defaultObject.c, d=defaultObject.d, e=defaultObject.e} = defaultObject)
function foo(object = {}) {
    object = { b=1, c=99, d=88, ...object }
    //Continue the function code..
}

跟进: 如果你需要类型和默认值(并且你不想声明一个接口),你可以这样写:

function foo(params: {a?: string, b?: number, c?: number, d?: number, e?: string}) {
    params = { b:1, c:99, d:88, ...params }
    //Continue the function code..
}

其他回答

接口的默认值是不可能的,因为接口只存在于编译时。

可选择的解决方案:

例子:

class AnotherType {}

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

function makeIX (): IX {
    return {
    a: 'abc',
    b: null,
    c: null
    }
}

const x = makeIX();

x.a = 'xyz';
x.b = 123;
x.c = new AnotherType();

关于你的例子,我唯一改变的是使属性c both AnotherType |为空。这将是必要的,没有任何编译器错误(这个错误也出现在你的例子中,你初始化为null属性c)。

您可以使用两个单独的配置。一个作为具有可选属性的输入(将具有默认值),另一个仅具有必需的属性。这可以通过&和Required来方便:

interface DefaultedFuncConfig {
  b?: boolean;
}

interface MandatoryFuncConfig {
  a: boolean;
}

export type FuncConfig = MandatoryFuncConfig & DefaultedFuncConfig;
 
export const func = (config: FuncConfig): Required<FuncConfig> => ({
  b: true,
  ...config
});

// will compile
func({ a: true });
func({ a: true, b: true });

// will error
func({ b: true });
func({});

你不能在接口中设置默认值,但是你可以通过使用可选属性来完成你想做的事情:

简单地将界面更改为:

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

你可以这样做:

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

如果没有设置这些属性,则使用init函数为x.b和x.c分配默认值。

虽然@Timar的答案是完美的空默认值(什么是被要求的),这里有另一个简单的解决方案,允许其他默认值:定义一个选项接口,以及一个根据常量包含默认值;在构造函数中,使用展开操作符设置options成员变量

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);
    }
}

现在你可以像这样使用这个类:

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

输出:

set
null
1

我使用下面的模式:

创建工具类型默认值<T>:

type OptionalKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? K : never }[keyof T];
type Defaults<T> = Required<Pick<T, OptionalKeys<T>>>

用选项/默认值声明类:

// options passed to class constructor
export interface Options {
    a: string,
    b?: any,
    c?: number
}

// defaults
const defaults: Defaults<Options> = {
    b: null,
    c: 1
};

export class MyClass {
    // all options in class must have values
    options: Required<Options>;

    constructor(options: Options) {
        // merge passed options and defaults
        this.options = Object.assign({}, defaults, options);
    }
}

创建类实例:

const myClass = new MyClass({
    a: 'hello',
    b: true,
});

console.log(myClass.options);
// { a: 'hello', b: true, c: 1 }