如何使用 class 作为带有打字稿的变量中的类型?

How to use a class as a type in a variable with typescript?

我对如何在打字稿中使用 OOP 有点困惑。

我习惯用PHP来做。

1 - 我可以使用 class 作为类型而不必填写所有属性值吗?

2 - 我真的需要创建一个接口来创建 class 属性并将其用作某些函数中的类型吗?

比如这是我的class:

class User {
  protected id: number;
  protected name: string;
  protected age?: Date;
  
  constructor(id: number, name: string, age: Date) {
    this.id = id;
    this.name = name;
    this.age = age;
  
  getId() return this.id;

  getName() return this.name;
  setName(value: string) this.name = value;

  getAge() return this.age;
  setAge(value: Date) this.age = value;
}

这是我的服务功能:

const test = () => {
  const user = new User({id: 1, name: 'Rick' });
}

我尝试了很多方法都返回了一些错误,这是主要的。

Type '{ id: string; name: string; }' is missing the following properties from type 'User': getId, getName, setName

我知道我可以使用界面来做到这一点,但我正在寻找一种没有界面的方法,如果可能的话。

这个怎么样...


class User {
    protected id: number;
    protected name: string;
    protected age?: Date;

    constructor({id, name, age }: { id: number, name: string, age?: Date }) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
}

const user1 = new User({id: 1, name: 'Rick' });
const user2 = new User({id: 1, name: 'Rick', age: undefined });
const user3 = new User({id: 1, name: 'Rick', age: new Date() });

// const user4= new User({id: 1, name: 'Rick', age: new Date(), addProp: [] }); // <== Error

Typescript 文档确实有一节关于 Parameter Destructuring

如果我们觉得太冗长,我们可以为构造函数的参数类型定义一个type alias,比如...

type UserParams = { id: number, name: string, age?: Date };

class User {
    protected id: number;
    protected name: string;
    protected age?: Date;

    constructor({id, name, age }: UserParams) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
}

const user1 = new User({id: 1, name: 'Rick' });
const user2 = new User({id: 1, name: 'Rick', age: undefined });
const user3 = new User({id: 1, name: 'Rick', age: new Date() });

// const user4= new User({id: 1, name: 'Rick', age: new Date(), addProp: [] }); // <== Error

我们本可以在构造函数参数中使用class User作为类型,但问题是class User的所有属性都标记为[=具有这些属性名称的 16=] 和 passing-in 参数将出错。不过,如果我们能把这些属性做成public,应该就能达到我们想要的...

class User {
    id: number;   // <== protected modifier gone
    name: string; // <== protected modifier gone
    age?: Date;   // <== protected modifier gone

    constructor({ id, name, age }: User) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
}

const user1 = new User({ id: 1, name: 'Rick' });
const user2 = new User({ id: 1, name: 'Rick', age: undefined });
const user3 = new User({ id: 1, name: 'Rick', age: new Date() });

// const user4 = new User({ id: 1, name: 'Rick', age: new Date(), addProp: [] }); // <== Error

您可以将实施减少到一行:

class User {
    constructor(protected id: number, protected name: string, protected age?: Date) { }
}

// {
//     "id": 1,
//     "name": "2",
//     "age": undefined
// }
const result = new User(1, '2') // ok

PLayground