String.Format在TypeScript中不起作用

Ант*_*нов 43 javascript string string-formatting typescript

String.Format不起作用TypeScript.
错误:

The property 'format' does not exist on value of type 
 '{ prototype: String; fromCharCode(...codes: number[]): string; 
 (value?: any): string; new(value?: any): String; }'.
Run Code Online (Sandbox Code Playgroud)

attributes["Title"] = String.format(
    Settings.labelKeyValuePhraseCollection["[WAIT DAYS]"],
    originalAttributes.Days
);
Run Code Online (Sandbox Code Playgroud)

Fen*_*ton 103

字符串插值

注意:从TypeScript 1.4开始,TypeScript中提供了字符串插值:

var a = "Hello";
var b = "World";

var text = `${a} ${b}`
Run Code Online (Sandbox Code Playgroud)

这将编译为:

var a = "Hello";
var b = "World";
var text = a + " " + b;
Run Code Online (Sandbox Code Playgroud)

字符串格式

JavaScript String对象没有format函数.TypeScript不会添加到本机对象,因此它也没有String.format函数.

对于TypeScript,您需要扩展String接口,然后需要提供实现:

interface String {
    format(...replacements: string[]): string;
}

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用该功能:

var myStr = 'This is an {0} for {0} purposes: {1}';

alert(myStr.format('example', 'end'));
Run Code Online (Sandbox Code Playgroud)

可能还考虑串插,这是一个ECMAScript的6功能(模板字符串的功能) -尽管使用它的String.format使用情况下,你仍然需要将其包装在一个功能,以提供包含格式的原始字符串然后是位置参数.它通常与内插的变量一起使用,因此您需要使用参数进行映射以使其适用于此用例.

例如,格式字符串通常定义为稍后使用...这不起作用:

// Works
var myFormatString = 'This is an {0} for {0} purposes: {1}';

// Compiler warnings (a and b not yet defines)
var myTemplateString = `This is an ${a} for ${a} purposes: ${b}`;
Run Code Online (Sandbox Code Playgroud)

因此,要使用字符串插值而不是格式字符串,您需要使用:

function myTemplate(a: string, b: string) {
    var myTemplateString = `This is an ${a} for ${a} purposes: ${b}`;
}

alert(myTemplate('example', 'end'));
Run Code Online (Sandbox Code Playgroud)

格式字符串的另一个常见用例是它们被用作共享的资源.我还没有发现一种从数据源加载模板字符串而不使用的方法eval.

  • “JavaScript(**以及 TypeScript**)没有本机 String.Format 函数” - 这实际上是不正确的。TypeScript 中存在的许多东西 * JavaScript 中不存在(然而,与您所说的相反) (3认同)
  • 我没有说任何关于在 TypeScript 中扩展的任何本机对象,我说你写的陈述是不正确的。Type Script 是 Javascript 的**超集**,因此 TypeScript 中存在许多在 Javascript 中不存在的结构。[“在 1.4 版本中,TypeScript 现在支持 ES6 模板字符串,并且还可以将它们编译为 ES3/ES5 表达式”](http://blogs.msdn.com/b/typescript/archive/2015/01/16/annoucing -typescript-1-4.aspx)。如果 string.format 达到相同的结果,您将使用它。 (2认同)
  • @YannDuran 我已经改写了第一句话,以试图让它在人们只想单独阅读部分内容时仍然有效。JavaScript 中存在模板字符串 *do*。在编译器为旧目标添加 polyfill 的情况下,它*仍然* 不会添加到本机对象 - 它内联更改,或者(很少)添加一个特殊命名的函数。模板字符串不能满足 `String.format` 的所有用例。 (2认同)

g.p*_*dou 33

如果您的唯一目标是消除丑陋的字符串连接和无聊的字符串转换,您可以使用TypeScript的本机字符串插值:

var yourMessage = `Your text ${yourVariable} your text continued ${yourExpression} and so on.`
Run Code Online (Sandbox Code Playgroud)

注意:

在赋值语句的右侧,分隔符既不是单引号也不是双引号,而是一个称为反引号或重音符特殊字符.

TypeScript编译器会将右侧特殊文字转换为字符串连接表达式.换句话说,此语法不依赖于ECMAScript 6功能而是依赖于本机TypeScript功能.您生成的javascript代码仍然兼容.

  • 在我看到关于特殊刻度标记的注释并意识到我做错了之前,我无法进行字符串插值工作最长时间. (2认同)

SLd*_*gon 9

如果您使用 NodeJS,则可以使用内置 util 函数:

import * as util from "util";
util.format('My string: %s', 'foo');
Run Code Online (Sandbox Code Playgroud)

文档可以在这里找到: https ://nodejs.org/api/util.html#util_util_format_format_args


bas*_*rat 6

您可以很容易地声明它:

interface StringConstructor {
    format: (formatString: string, ...replacement: any[]) => string;
}

String.format('','');
Run Code Online (Sandbox Code Playgroud)

假设String.format是在其他位置定义的。例如在Microsoft Ajax工具包中:http : //www.asp.net/ajaxlibrary/Reference.String-format-Function.ashx


Ana*_*hag 6

我是这样解决的;

1.创建函数

export function FormatString(str: string, ...val: string[]) {
  for (let index = 0; index < val.length; index++) {
    str = str.replace(`{${index}}`, val[index]);
  }
  return str;
}
Run Code Online (Sandbox Code Playgroud)

2.如下使用;

FormatString("{0} is {1} {2}", "This", "formatting", "hack");
Run Code Online (Sandbox Code Playgroud)