How to ensure TypeScript that string|string[] is string without using as?

前端 未结 2 2015
旧时难觅i
旧时难觅i 2021-01-20 04:32

edit
Due to course of time, this question has lost its validity, as it seems from the comments and answers to this one. Despite initial appearance, it\

2条回答
  •  梦毁少年i
    2021-01-20 04:38

    Besides generics you can use function overloading

    function getI18n(id: string[]): string[];
    function getI18n(id: string): string;
    function getI18n(id: string | string[]): string | string[] {
        if (typeof id === 'string') {
            return id + '_title';
        }
        return id.slice();
    }
    
    const title = getI18n('test'); // const title: string
    const titles = getI18n(['a', 'b', 'c']); // const titles: string[]
    

    Link to official docs on this feature: functions overloads

提交回复
热议问题