LoginSignup
1
0

More than 3 years have passed since last update.

変数の定義を省略して複数のフィールドに代入する[TypeScript]

Last updated at Posted at 2020-07-21

記事の命名が迷子

やりたいこと

こういったオブジェクトがあって、

interface UserProperties {
    userid: number;
    username: string;
}

const getUserProperties = (): UserProperties => ({
    userid: 1,
    username: 'おなまえ',
});

別のオブジェクトの引数なんかにに代入したい

class User {
    id: number;
    name: string;
    constructor(params: { id: number; name: string }) {
        this.name = params.name;
        this.id = params.id;
    }
}

変数を定義してから

const props = getUserProperties();
const user = new User({ id: props.userid, name: props.username });

定義せずに

const user = new User(
    ((props: UserProperties) => ({
        id: props.userid,
        name: props.username,
    }))(getUserProperties()),
);

定義せずに書くと

読みにくい

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0