打字稿,将接口键转换为可能的字符串值的枚举

时间:2020-10-19 16:29:35

标签: typescript

假装我有一个像这样的界面:

<?php

namespace App\Http\Livewire\Products\Variations;

use App\Models\Variation;
use Livewire\Component;

class Index extends Component
{

    public $moreValues = [0];

    public $editMode = false;

    public $name, $values = [];

    protected $rules = [
        'name' => 'required|string',
        'values.*' => 'required|string',
    ];

    public function addRowForValue()
    {
        $this->moreValues[] += 1;
    }

    public function removeRowForValue($key)
    {
        unset($this->moreValues[$key]);
    }

    public function store()
    {
        $this->validate();

        $variation = Variation::create([
            'name' => $this->name
        ]);

        foreach ($this->values as $key => $value) {
            $variation->values()->create([
                'value' => $this->values[$key]
            ]);
        }

        session()->flash('message', 'Unit create successfully.');

        $this->clearForm();
    }

    /**
     * @param $id
     */
    public function edit($id)
    {
        $this->editMode = true;

        $this->moreValues = [0];

        $this->resetErrorBag();

        $this->clearForm();

        // fill the form here with data
        $variation = Variation::query()->findOrFail($id);

        $this->name = $variation->name;

        $this->values = [];

        foreach ($variation->values as $key => $value) {

            // incrementing input by value
            $this->moreValues[$key] = $value;

            // showing value their own field
            $this->values[$key] = $value;
        }

        $this->emit('openModal');
    }

    protected function clearForm()
    {
        $this->name = '';
        $this->values = '';
    }

    public function render()
    {
        $variations = Variation::with('values')->latest('id')->get();

        return view('livewire.products.variations.index', compact('variations'))
            ->extends('layouts.app');
    }
}

从这个界面,我想动态创建一个联合类型,其可能的值为'keyA','keyB'和'keyC'。

如果我必须手动创建它,将导致类似以下内容的

$products = json_decode($products, true);  // When TRUE, JSON objects will be returned as associative arrays

foreach($products as $product){
    echo $product['id']; 
}

使用Typescript可以实现吗?

1 个答案:

答案 0 :(得分:3)

尝试一下:

export type MyType = keyof MyInterface;