是否可以从TypeScript接口创建“空”对象?

时间:2020-05-08 11:59:29

标签: javascript typescript constructor interface typescript-typings

假设您有一个很大的对象定义为TypeScript接口:

interface AccountInterface {
  accountIdentifier?: string;
  sid?: string;
  idToken?: {
    aio?: string;
  };
  idTokenClaims?: {
      aio?: string;
  };
}

我希望对象始终具有其属性和子属性。它们可以是字符串或空字符串:

let account = {
  accountIdentifier: "",
  sid: "",
  idToken: {
    aio: "",
  },
  idTokenClaims: {
    aio: "",
  },
};

阅读其他我认为有可能做到的问题:

const emptyAccount = {} as AccountInterface

console.log('emptyAccount ', emptyAccount)
console.log('emptyAccount.sid ', emptyAccount.sid)

但是,这并不能创建一个具有所有属性的对象,并根据需要将其作为空字符串。

如果可能会发生类似的事情,那将是很好的,因此不需要在代码中重复该对象,例如,一个用于接口,一个用于具有空字符串属性的对象。

2 个答案:

答案 0 :(得分:4)

您可以创建一个class that implements that interface,添加默认值,然后使用该值创建对象。您仍在其他地方重新编写相同的结构,但是现在只需要执行一次,就可以使用constructor来用不同的值初始化对象。

interface AccountInterface {
  accountIdentifier?: string;
  sid?: string;
  idToken?: {
      aio?: string;
  };
  idTokenClaims?: {
      aio?: string;
  };
}

class Account implements AccountInterface {
  accountIdentifier = '';
  sid = '';
  idToken = { aio: '' };
  idTokenClaims = { aio: '' };
}

const emptyAccount = new Account();

此外,正如@apokryfos指出的那样,您还可以使用该类来键入对象,因此,无需定义instanceclass,除非您要使对象实现没有使用该类创建的实例(因为那些实例没有在类中定义的方法)。

如果您想避免使用class并使用function做类似的事情,则完全可以:

function createAccount(): AccountInterface {
  return {
    accountIdentifier = '';
    sid = '';
    idToken = { aio: '' };
    idTokenClaims = { aio: '' };
  };
}

const emptyAccount = createAccount();

答案 1 :(得分:0)

const emptyAccount = {} as AccountInterface应该创建一个对象。但是您的AccountInterface仅包含可能存在但不存在的属性(由于?)。因此,空对象与您的AccountInterface完全匹配。

如果要具有包含默认值的属性,则必须在接口中声明它。

interface AccountInterface {
    accountIdentifier: string|null // <- will be included in {} as AccountInterface
    sid?: string // <- will not be included in {} as AccountInterface
}